WolframLang: Define Function by Pattern

By Xah Lee. Date: . Last updated: .

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:

  1. define a delayed replacement rule SetDelayed[pattern,result]
  2. The fullform of x_ is Pattern[x, Blank[]]. It means, a Blank[] that matches anything, and giving it a name x. Pattern
  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.

Set vs SetDelayed

WolframLang: Define Function

WolframLang in Depth

Basics

Comment, Print

String

Arithmetic

List

Expression, Atom, Head

Boolean

Conditional

Variable

Loop

Data Structure

Function

Pattern Matching

Advanced

Shell Tasks

Misc