Functions can be defined in the following way:
f[x_] := x ^ 2
This tells Mathics to replace every occurrence of f
with one (arbitrary) parameter x
with x ^ 2
.
f[3]
f[a]
The definition of f
does not specify anything for two parameters, so any such call will stay unevaluated:
f[1, 2]
In fact, functions in Mathics are just one aspect of patterns: f[x_]
is a pattern that matches expressions like f[3]
and f[a]
. The following patterns are available:
_
or Blank[]
Pattern[x, p]
x_
or Pattern[x, Blank[]]
__
or BlankSequence[]
___
or BlankNullSequence[]
_h
or Blank[h]
x_h
or Pattern[x, Blank[h]]
p | q
or Alternatives[p, q]
p ? t
or PatternTest[p, t]
t[p]
yields True
.
p /; c
or Condition[p, c]
Verbatim[p]
As before, patterns can be used to define functions:
g[s___] := Plus[s] ^ 2
g[1, 2, 3]
MatchQ[e, p]
tests whether e matches p:
MatchQ[a + b, x_ + y_]
MatchQ[6, _Integer]
ReplaceAll
(/.
) replaces all occurrences of a pattern in an expression using a Rule
given by ->
:
{2, "a", 3, 2.5, "b", c} /. x_Integer -> x ^ 2
You can also specify a list of rules:
{2, "a", 3, 2.5, "b", c} /. {x_Integer -> x ^ 2.0, y_String -> 10}
ReplaceRepeated
(//.
) applies a set of rules repeatedly, until the expression doesn't change anymore:
{2, "a", 3, 2.5, "b", c} //. {x_Integer -> x ^ 2.0, y_String -> 10}
There is a “delayed” version of Rule
which can be specified by :>
(similar to the relation of :=
to =
):
a :> 1 + 2
a -> 1 + 2
This is useful when the right side of a rule should not be evaluated immediately (before matching):
{1, 2} /. x_Integer -> N[x]
Here, N
is applied to x
before the actual matching, simply yielding x
. With a delayed rule this can be avoided:
{1, 2} /. x_Integer :> N[x]
While ReplaceAll
and ReplaceRepeated
simply take the first possible match into account, ReplaceList
returns a list of all possible matches. This can be used to get all subsequences of a list, for instance:
ReplaceList[{a, b, c}, {___, x__, ___} -> {x}]
ReplaceAll
would just return the first expression:
ReplaceAll[{a, b, c}, {___, x__, ___} -> {x}]
In addition to defining functions as rules for certain patterns, there are pure functions that can be defined using the &
postfix operator, where everything before it is treated as the funtion body and #
can be used as argument placeholder:
h = # ^ 2 &;
h[3]
Multiple arguments can simply be indexed:
sum = #1 + #2 &;
sum[4, 6]
It is also possible to name arguments using Function
:
prod = Function[{x, y}, x * y];
prod[4, 6]
Pure functions are very handy when functions are used only locally, e.g., when combined with operators like Map
:
# ^ 2 & /@ Range[5]
Sort according to the second part of a list:
Sort[{{x, 10}, {y, 2}, {z, 5}}, #1[[2]] < #2[[2]] &]
Functions can be applied using prefix or postfix notation, in addition to using []
:
h @ 3
3 // h