WolframLang: Define Function by Pattern
Function can be defined by using pattern matching. First, we show common examples. Then, we show how it works.
Function with One Parameter
(* define a replacement rule, that changes f[any_one_thing] to any_one_thing + 1 *) f[x_] := x + 1; f[3] === 4
Function with 2 parameters
Clear[ f ]; f[x_, y_] := x + y; f[3, 4] === 7
Function with rest parameters
Clear[ f ]; (* 1 or more arguments *) f[x__] := List[ x ] ; f[3] === {3} f[3, 4] === {3, 4} f[3, 4, 5] === {3, 4, 5}
Clear[ f ]; (* require 2 or more args. first is x *) f[x_, y__] := List[ x, y ] ; f[3] === f[3] (* when no pattern matches, nothing is changed *) f[3, 4] === {3, 4} f[3, 4, 5] === {3, 4, 5}
Function with Default Value for Parameter
Clear[ f ]; f[x_:3] := List[ x ] ; (* no arg. default to 3 *) f[] === {3} f[2] === {2}
Clear[ f ]; f[x_:3, y_:4] := List[ x, y ] ; f[] === {3, 4} f[2] === {2, 4} f[8,9] === {8, 9}
Function Behavior Depending on Argument Type (aka Polymorphism)
Clear[ f ]; (* if arg is a list, return 3 *) f[x_List] := 3 ; (* if arg is an integer, return 4 *) f[x_Integer] := 4 ; (* if arg is an approx number, return 5 *) f[x_Real] := 5 ; f[{a,b}] === 3 f[3] === 4 f[3.1] === 5
How Does Function by Pattern Matching Work
Function defined by using pattern matching, effectively is defining a syntactic replacement rule (aka, a term-rewriting rule). It has this form:
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 *) 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,replacement]
. (delayed means, don't eval the replacement until the replacement happens.) [see WolframLang: Set and SetDelayed] - The FullForm of
x_
isPattern[x, Blank[]]
. It means, aBlank[]
that matches anything, and giving it a namex
. [see WolframLang: Pattern Syntax] 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.