问题
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}]
is not okay since it only Or
'ed the first two elements in the list. Many thanks!
回答1:
This will work, no matter how many vars, and is a general pattern:
Or[##]&,
for example
In[5]:= Or[##] & @@ {a, b, c}
Out[5]= a || b || c
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
This will be ok though:
Function[Null,Or[##],HoldAll],
for example,
In[8]:= Function[Null, Or[##], HoldAll] @@ Hold[True, Print["*"]]
Out[8]= True
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
回答2:
Or @@ {a, b, c}
Equivalent
Apply[Or, {a, b, c}]
Equivalent
{a, b, c} /. {x_, y__} -> Or[x, y]
Apply works like this:
{2 #1, 3 #2, 4 #3} & @@ {a, b, c}
{2 a, 3 b, 4 c}
Plus[2 #1, 3 #2, 4 #3] & @@ {a, b, c}
2 a + 3 b + 4 c
回答3:
Are you sure you are expecting the right thing from Apply? If you look in the documentation, http://reference.wolfram.com/mathematica/ref/Apply.html, you will see that Apply[f,expr] simply replaces the head of f by expr. It does not, in general, give f[expr].
If you wish to operate with function f onto expr, try f@expr or f[expr].
Perhaps you understand the above and your question really is, "how do I define some f that, when I do Apply[f,{a,b,c}]
, does the same job as Or[a,b,c]
. Is that it?
来源:https://stackoverflow.com/questions/4867076/how-should-i-write-a-function-to-be-used-in-apply-in-mathematica