WolframLang: Define Function by Pattern
Function can be defined by Function
.
[see WolframLang: Define Function]
Function can also be defined by using pattern matching. That is, you define a replacement rule
left-hand-side := right-hand-side
, and whenever the pattern on the left-hand-side occur, it is replaced by the right-hand-side during evaluation.
(* define a replacement rule, that changes f[anything] to anything + 1 *) (* effectively, a function named f that adds 1 to arg *) f[x_] := x + 1; f[3] === 4
The FullForm syntax for
f[x_] := x + 1
is
SetDelayed[
f[Pattern[x, Blank[]]],
Plus[x, 1]
]
This means:
- define a delayed replacement rule
SetDelayed[pattern,result]
- The fullform of
x_
isPattern[x, Blank[]]
. It means, aBlank[]
that matches anything, and giving it a namex
. Pattern f[x_]
means a pattern that'sf
followed by square brackets, with anything inside, and this anything is namedx
.- Whenever the left-hand-side occur when evaluating expression, replace it by
x + 1
.
Transformation of expression by symbolic pattern matching is a major mechanism of how WolframLang does computation. (called term rewriting system)
Most functions in WolframLang are written this way.