WolframLang: Define Function by Pattern

By Xah Lee. Date: . Last updated: .

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 WolframLang: Pattern Syntax]

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. 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:

  1. define a delayed replacement rule SetDelayed[pattern, replacement]. (delayed means, don't eval the replacement until the replacement happens.) [see WolframLang: Set, SetDelayed]
  2. The FullForm of x_ is Pattern[x, Blank[]]. It means, a Blank[] that matches anything, and giving it a name x. [see WolframLang: Pattern Syntax]
  3. f[x_] means a pattern that's f followed by square brackets, with anything inside, and this anything is named x.
  4. 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.

WolframLang: Define Function