问题描述
我想要一个函数 AnyTrue[expr,{i,{i1,i2,...}}]
来检查 expr
是否为 True
for any i1,i2...
它应该就像 AnyTrue
是 Table
后跟 Or@@%
,区别在于它只计算 expr
直到找到第一个 True
.
I'd like a function AnyTrue[expr,{i,{i1,i2,...}}]
which checks if expr
is True
for any of i1,i2...
It should be as if AnyTrue
was Table
followed by Or@@%
, with the difference that it only evaluates expr
until first True
is found.
短路部分是可选的,我真正想知道的是模拟Table
的非标准评估序列的正确方法.
Short-circuiting part is optional, what I'd really like to know is the proper way to emulate Table
's non-standard evaluation sequence.
11/14 更新
这是迈克尔的解决方案,您可以使用它来链接所有"和存在"检查
Here's a solution due to Michael, you can use it to chain "for all" and "there exists" checks
SetAttributes[AllTrue, HoldAll];
SetAttributes[AnyTrue, HoldAll];
AllTrue[{var_Symbol, lis_List}, expr_] :=
LengthWhile[lis,
TrueQ[ReleaseHold[Hold[expr] /. HoldPattern[var] -> #]] &] ==
Length[lis];
AnyTrue[{var_Symbol, lis_List}, expr_] :=
LengthWhile[lis,
Not[TrueQ[ReleaseHold[Hold[expr] /. HoldPattern[var] -> #]]] &] <
Length[lis];
AllTrue[{a, {1, 3, 5}}, AnyTrue[{b, {2, 4, 5}}, EvenQ[a + b]]]
AnyTrue[{a, {1, 3, 5}}, AllTrue[{b, {2, 4, 5}}, EvenQ[a + b]]]
推荐答案
这个怎么样?
SetAttributes[AnyTrue, HoldAll];
AnyTrue[expr_, {var_Symbol, lis_List}] :=
LengthWhile[lis,
Not[TrueQ[ReleaseHold[Hold[expr] /. HoldPattern[var] -> #]]] &
] < Length[lis]
通过 LengthWhile
包括短路,并在必要时保留所有内容,以便事情按预期工作,var
具有函数外的值:
Includes short-circuiting via LengthWhile
and keeps everything held where necessary so that things work as expected with var
has a value outside the function:
In[161]:= x = 777;
In[162]:= AnyTrue[Print["x=", x]; x == 3, {x, {1, 2, 3, 4, 5}}]
During evaluation of In[162]:= x=1
During evaluation of In[162]:= x=2
During evaluation of In[162]:= x=3
Out[162]= True
内置的 Or
也是短路的,因为它的价值.(但我意识到用例如 Table
来构建未评估的术语是一种痛苦):
The built-in Or
is short-circuiting, too, for what it's worth. (but I realize building up the unevaluated terms with e.g. Table
is a pain):
In[173]:= Or[Print[1];True, Print[2];False]
During evaluation of In[173]:= 1
Out[173]= True
这篇关于具有非标准评估的自定义函数(行为类似于 Table)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!