Pattern Matching
Stratego -- Strategies for Program Transformation
The match strategy (
?
) Compares the term under consideration to a
pattern. If the pattern contains variables, these variables are bound
to the actual values in the term.
Special matching operators exist:
#
and
@
. They are explained in
their own paragraph.
For example,
?FunDef(Id(fn),fb)
- succeeds when applied to
FunDef(Id("decode"),Return(Int(0)))
, fn
will have the value "decode"
, and fb
will have the value Return(Int(0))
- fails when applied to e.g. term
VarDef(Id("i"),TypeDecl(Int))
Matching on lists:
explained using some examples:
0: ?[x | xs] applied to [] will fail
1: ?[x | xs] applied to [1] will yield x = 1, xs = []
2: ?[x | xs] applied to [1,2] will yield x = 1, xs = [2]
3: ?[x | xs] applied to [1,2,3,4] will yield x = 1, xs = [2,3,4]
4: ?[x , xs] applied to [] will fail
5: ?[x , xs] applied to [1] will fail
6: ?[x , xs] applied to [1,2] will yield x = 1, xs = 2
7: ?[x , xs] applied to [1,2,3,4] will fail
?[] will only succeed on an empty list []
See also
- TermProject
- Contextual pattern matching?
- Term deconstruction?
- Variable Scope?