我应该如何编写一个在 Mathematica 中应用的函数? [英] How should I write a function to be used in Apply in Mathematica?
问题描述
我想知道如何编写一个在 Mathematica 的 Apply
函数中使用的函数?例如,我想简单地重新实现 Or
功能,我发现了以下
I am wondering how I can write a function to be used in the Apply
function in Mathematica? For example, I want to trivially re-implement the Or
function, I found the following
Apply[(#1 || #2)&,{a,b,c}]
不好,因为它只对列表中的前两个元素进行了 Or
处理.非常感谢!
is not okay since it only Or
'ed the first two elements in the list. Many thanks!
推荐答案
这将有效,无论有多少变量,并且是通用模式:
This will work, no matter how many vars, and is a general pattern:
Or[##]&,
例如
In[5]:= Or[##] & @@ {a, b, c}
Out[5]= a || b || c
然而,在 Or
的情况下,这还不够好,因为 Or
是 HoldAll
并且短路 - 即,它在第一个 True
语句处停止,并保持其余的不求值.示例:
However, in the case of Or
, this is not good enough, since Or
is HoldAll
and short-circuiting - that is, it stops upon first True
statement, and keeps the rest unevaluated. Example:
In[6]:= Or[True, Print["*"]]
Out[6]= True
In[7]:= Or[##] & @@ Hold[True, Print["*"]]
During evaluation of In[7]:= *
Out[7]= True
不过没关系:
Function[Null,Or[##],HoldAll],
例如
In[8]:= Function[Null, Or[##], HoldAll] @@ Hold[True, Print["*"]]
Out[8]= True
并且可以在这种情况下使用(当您不希望您的参数进行评估时).请注意,这使用了一种未记录的 Function
形式.R.Maeder 的Programming in Mathematica"一书中提到了这种形式.
and can be used in such cases (when you don't want your arguments to evaluate). Note that this uses an undocumented form of Function
. The mention of this form can be found in the book of R.Maeder, "Programming in Mathematica".
HTH
这篇关于我应该如何编写一个在 Mathematica 中应用的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!