Function Aliases
Mathematica has a series of useful function aliases that make coding more concise and readable.
Technically, these are called infix operators , a term that also encapsulates +
, -
, and *
, but that’s unimportant for their usage here.
@ (Prefix)
The @
alias is like a pair of square brackets. The following illustrates its usage:
N@π
(*Out:*)
3.141592653589793`
It only applies to a single argument however. For example, Mathematica will not evaluate the following command
N@π,12
/@ (Map)
/@
takes a function and applies to every element in a list, returning the list of results. Example:
Sin/@(π*{0,1/4,1/2,3/4,1,1+1/4,1+1/2,1+3/4,2})
(*Out:*)
{0,,1,,0,-,-1,-,0}
When using this alias care should be taken that the right-hand side is wrapped in parentheses, as was done above, if it’s more than just a simple list.
@@ (Apply)
@@
applies a function to all the arguments in a list. That is, the elements of the list become the arguments to the function. Example:
N@@{π,12}
(*Out:*)
3.14159265358979323846264338327950419984`12.
// (Postfix)
//
is more or less a reversed form of @
. Example:
π//N
(*Out:*)
3.141592653589793`
But there is a small difference in terms of how the two work with other operators.
Consider you’re trying to apply the function f
to the list of results generated by using g/@{1,2,3,4}
One might first try the following:
f@g/@{1,2,3,4}
(*Out:*)
{f[g][1],f[g][2],f[g][3],f[g][4]}
This clearly doesn’t work. f
is applied to g
before being mapped across {1,2,3,4}
.
In this case there are two options:
f@(g/@{1,2,3,4})
(*Out:*)
f[{g[1],g[2],g[3],g[4]}]
or
g/@{1,2,3,4}//f
(*Out:*)
f[{g[1],g[2],g[3],g[4]}]
because /@
evaluates before //
, this works. What is said is that //
has a low precedence .
Precedences for any operator can be checked using the function Precedence
, if the function name is known. Function names for a given operator can be found by selecting the operator and using ––F on Mac or F1 on Windows.
For example, knowing that //
is an alias for the function Postfix
Precedence@Postfix
(*Out:*)
70.`
And we’ll compare that to the function Prefix
for which @
is an alias
Prefix//Precedence
(*Out:*)
640.`
~ (Infix)
~
takes a function and applies it to the preceding and following arguments as follows:
π~N~12
(*Out:*)
3.14159265358979323846264338327950419984`12.
This is useful and worth knowing, but it can often be cleaner simply to use @@
, potentially in combination with //
@*
(Composition)
@*
takes a two functions and composes them. For example:
(f@*g)[1]
(*Out:*)
f[g[1]]
This is particularly useful when negating a function, that is, applying the Not
function to it. We can make a simple NotTrueQ
function by doing this:
NotTrueQ = (Not@*TrueQ);
NotTrueQ@1
NotTrueQ@False
NotTrueQ@True
(*Out:*)
True
(*Out:*)
True
(*Out:*)
False