Functions and patterns

Functions can be defined in the following way:

This tells Mathics 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 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[]
matches one expression.
Pattern[xp]
matches the pattern p and stores the value in x.
x_ or Pattern[x, Blank[]]
matches one expression and stores it in x.
__ or BlankSequence[]
matches a sequence of one or more expressions.
___ or BlankNullSequence[]
matches a sequence of zero or more expressions.
_h or Blank[h]
matches one expression with head h.
x_h or Pattern[x, Blank[h]]
matches one expression with head h and stores it in x.
p | q or Alternatives[pq]
matches either pattern p or q.
p ? t or PatternTest[pt]
matches p if the test t[p] yields True.
p /; c or Condition[pc]
matches p if condition c holds.
Verbatim[p]
matches an expression that equals p, without regarding patterns inside p.

As before, patterns can be used to define functions:

MatchQ[ep] tests whether e matches p:

ReplaceAll (/.) replaces all occurrences of a pattern in an expression using a Rule given by ->:

You can also specify a list of rules:

ReplaceRepeated (//.) 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:

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:

ReplaceAll would just return the first expression:

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:

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 according to the second part of a list:

Functions can be applied using prefix or postfix notation, in addition to using []: