This is a note on the syntax and logic of Mathematica functions
Apply
, Map
, MapThrough
,
MapAll
, etc.
Apply
and infixes @
, @@
,
and @@@
f@expr
is the infix format of f[expr]
,
e.g. f@x
is f[x]
, and
f@{x,y,...}
is f[{x, y, ...}]
.
f@@expr
the infix format of Apply[f,
expr]
, and is Apply[f, expr, {0}]
with the
default level specification {0}
omitted. Here the
{0}
specifies that the level-0 subexpression, i.e.
expr
itself is the target of operation. And the
operation is to replace the operand's head with f
.
Therefore f@@h0[x, y, ...]
is Apply[f,
h0[x,y,...], {0}]
and evaluates to f[x,y, ...]
after replacing the level-0 expression's head h0
by
f
.
f@@@expr
is the infix format of Apply[f,
expr, {1}]
, which means to replace the level-1
subexpressions' heads by f
, e.g. f@@@h0[h1[x1,
x2, ...], h2[y], z, ...]
is Apply[f, h0[h11[x1, x2,
...], h12[y], z, ..., {1}]
and evaluates to h0[f[x1,
x2, ...], f[y], z, ...]
after replacing h11
and
h12
by f
. Note z
doesn't
have a head h13
on it and doesn't change.
In[1]:= f@@@h0[h1[x1,x2],h2[y],z]
Out[1]= h0[f[x1,x2],f[y],z]
The level refers to the different substructures of an expression
that can be accessed using Part
with the level
specification
In[2]:= expr={{x1,x2},y};
Part[expr,0]
Part[expr,1]
Part[expr,2]
Part[expr,{1,0}]
Part[expr,{1,1}]
Part[expr,{1,2}]
Part[expr,{2,0}]
Out[2]= List
Out[3]= {x1,x2}
Out[4]= y
Out[5]= {{x1,x2},List}
Out[6]= {{x1,x2},{x1,x2}}
Out[8]= {{x1,x2},y}
Out[9]= {y,List}
Map
and infix /@
, MapAll
and infix //@
f /@ expr
assigns f
to each level-1
part of expression and Apply
it, e.g.
In[9]:= f/@h0[x,y,z]
Out[9]= h0[f[x],f[y],f[z]]
f //@ expr
assigns f
to each part of
expression at all levels and Apply
it, e.g.
In[10]:= f//@{{x1,x2},y,z}
Out[10]= f[{f[{f[x1],f[x2]}],f[y],f[z]}]