How should I write a function to be used in Apply in Mathematica?

你说的曾经没有我的故事 提交于 2019-12-04 12:11:30

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

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

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?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!