Wolfram: Pattern Matching and Level Spec
Specify Depth Level of Expression for Pattern Matching
A important aspect of pattern matching is at what depth levels of an expression to match.
For example, if the pattern is
{x_, y_}
and the expression is
{1,{2,{3,4}}}
, it can match any of
{3,4}→ x match 3, y match 4{2,{3,4}}→ x match 2, y match {3,4}{1,{2,{3,4}}}→ x match 1, y match {2,{3,4}}
depending on the Level Spec (Tree Depth) used.
(* importance of level spec for patterns *) (* s------------------------------ *) (* match at level 0 only *) Replace[ {1,{2,{3,4}}}, {x_, y_} -> g[x,y], {0}] (* g[1, {2, {3, 4}}] *) (* s------------------------------ *) (* match at level 1 only *) Replace[ {1,{2,{3,4}}}, {x_, y_} -> g[x,y], {1}] (* {1, g[2, {3, 4}]} *) (* s------------------------------ *) (* match at level 2 only *) Replace[ {1,{2,{3,4}}}, {x_, y_} -> g[x,y], {2}] (* {1, {2, g[3, 4]}} *) (* s------------------------------ *) (* match at level 1 to Infinity *) Replace[ {1,{2,{3,4}}}, {x_, y_} -> g[x,y], {1,Infinity}] (* {1, g[2, g[3, 4]]} *) (* match at level 0 to Infinity *) Replace[ {1,{2,{3,4}}}, {x_, y_} -> g[x,y], {0,Infinity}] (* g[1, g[2, g[3, 4]]] *)