Suppose I have an expression and want to match it against successive patterns and return an expression corresponding to the first pattern that matched. In that case, I can use
Switch[expr,
pat1, val1,
pat2, val2,
…]
For example,
Switch[x,
_Integer, "This is an integer"],
_Real , "This is a real"],
_, "This is something else"]
However, the vali
cannot refer to parts of the pati
by name. i.e. I cannot do:
Switch[x,
i_Integer, ToString[i] <> " is an integer",
x_Real , ToString[x] <> " is a real",
e_, ToString[e] <> " is something else"]
Ocaml has the match
function, which is used as:
match expr in:
| pat1 -> val1
| pat2 -> val2
...
where the vali
can refer to named parts of the pati
. How can this most elegantly be accomplished in Mathematica?
Switch[x, _Integer, ToString[x] <> " is an integer",...]
$\endgroup$ – Dr. belisarius Apr 7 '14 at 12:21