Functions and patterns
Symja implements a Term rewriting system. Here we describe how the rewriting rules can be defined with function and pattern notation.
Functions can be defined in the following way:
This tells Symja to replace every occurrence of f
with one (arbitrary) parameter x
with x ^ 2
.
The definition of f does not specify anything for two parameters, so any such call will stay unevaluated:
In fact, functions in Symja 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:
matches one expression.
matches one expression and stores it in
x
.
matches a sequence of one or more expressions.
matches a sequence of zero or more expressions.
matches one expression with head
h
.
matches one expression with head
h
and stores it inx
.
or
matches either pattern
p
orq
.
or
matches
p
if the testt(p)
yieldsTrue
.
or
matches
p
if conditionc
holds.
As before, patterns can be used to define functions:
MatchQ(e, p)
tests whether e
matches p
:
ReplaceAll
(operator /.
) replaces all occurrences of a pattern in an expression using a Rule
given by ->
:
You can also specify a list of rules:
ReplaceRepeated
(operator //.
) applies a set of rules repeatedly, until the expression doesn’t change anymore:
There is a “delayed” version of Rule
which can be specified by :>
(similar to the relation of :=
to =
):
This is useful when the right side of a rule should not be evaluated immediately (before matching):
Here, N
is applied to x before the actual matching, simply yielding x. With a delayed rule this can be avoided:
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 function body and #
can be used as argument placeholder:
Multiple arguments can simply be indexed:
It is also possible to name arguments using Function
:
Pure functions are very handy when functions are used only locally, e.g., when combined with operators like Map
:
Sort using the second element of a list as a key:
Functions can be applied using prefix or postfix notation, in addition to using ()
: