WolframLang: Pattern Matching and Level Spec

By Xah Lee. Date: . Last updated: .

Pattern Matching and Level Spec

Depth Range (Level) of Tree to Match

A important aspect of pattern matching is at what tree depth levels of an expression to match.

For example, if the pattern is

{_,_}

and the expression is

{1,{2,{3,4}}}

, it can match any of

depending on the Level Spec (Tree Depth) used.

(* importance of level spec for patterns *)

(* match at level 1 to Infinity *)

Replace[ {1,{2,{3,4}}}, {x_, y_} -> g[x,y], {1,Infinity}]

(* {1, g[2, g[3, 4]]} *)

(* HHHH--------------------------------------------------- *)

(* match at level 1 only *)

Replace[ {1,{2,{3,4}}}, {x_, y_} -> g[x,y], {1}]

(* {1, g[2, {3, 4}]} *)

(* HHHH--------------------------------------------------- *)

(* match at level 2 only *)

Replace[ {1,{2,{3,4}}}, {x_, y_} -> g[x,y], {2}]

(* {1, {2, g[3, 4]}} *)

WolframLang, Tree Depth and Level Spec

Pattern Matching