Wolfram: 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
f[x_] := body
(* define a replacement rule, that changes f[thing] to thing + 1 *) f[x_] := x + 1; f[3] (* 4 *)
Function with 2 parameters
f[x_, y_] := body
Clear[ f ]; f[x_, y_] := x + y; f[3, 4] (* 7 *)
Function with Any Number of Parameters (Rest Parameter)
f[x__] := body
The double lowline __
is a pattern for one or more of anything.
〔see Wolfram: Pattern Syntax〕
Clear[ ff, gg ]; (* 1 or more arguments *) ff[x__] := gg[ x ] ; ff[3] === gg[3] (* True *) ff[3, 4] === gg[3, 4] (* True *) ff[3, 4, 5] === gg[3, 4, 5] (* True *)
Clear[ ff , gg ]; (* require 2 or more args. first is x *) ff[x_, y__] := gg[ x, y ] ; (* when no pattern matches, nothing is changed *) ff[3] === ff[3] (* True *) ff[3, 4] === gg[3, 4] (* True *) ff[3, 4, 5] === gg[3, 4, 5] (* True *)
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. It has this form:
left-hand-side := right-hand-side
whenever the pattern on the left-hand-side occur in evaluating any expression, the matched part is replaced by the right-hand-side.
(* 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 Wolfram: Set, SetDelayed〕 - The FullForm of
x_
isPattern[x, Blank[]]
. It means, aBlank[]
that matches anything, and giving it a namex
. 〔see Wolfram: 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.