Functions and Patterns

Functions can be defined in the following way:

This tells Mathics3 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 Mathics3 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[x, p]

matches the pattern p and stores the matching sub-expression into 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[p, q]

matches either pattern p or q.

p ? t or PatternTest[p, t]

matches p if the test $t[p]$ yields True.

p /; c or Condition[p, c]

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:

ReplaceAll and ReplaceRepeated take the first possible match.
However 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 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 []:

Formatting Output
Graphics Introduction Examples