"matched" Set[]

• To: mathgroup at smc.vnet.net
• Subject: [mg91619] "matched" Set[]
• From: "厉正吉" <zhengji.li at gmail.com>
• Date: Fri, 29 Aug 2008 04:12:14 -0400 (EDT)

```I have used Erlang (http://www.erlang.org) sometimes, and find its
assignment statement is *amazing*. As an example,

{ok, Value} = module:foo(..., ...).

If this function successfully done the operation, then it will return
{ok, Result}, then Result is assigned to Value; if not, it will return
assigned to (or more exactly,  "does not match") "ok", and an
exception is raised at runtime. This is really COOL.

So, I want such feature in Mathematica too, and have written a Match
function attached at the end of this mail. With it, I can do things
like this:

Match[1234, V] = {1234, 4321}; ===> V = 4321.
Match[1234, V] = {4321, 4321}; ===> Throw::nocatch: .......

This "Match" is still not perfect yet: the result of expression
(Match[1234, V] = {1234, 4321}) is 4321, maybe {1234, 4321} is much
better, like what Set[] alway does.

I find such a "Match" is quite useful when writing a parser in
Mathematica from scratch.

====================== Souce code of Match  ======================
Attributes[Match] = {HoldAll};
Match /: Set[Match[lhs_Symbol], rhs_] := (lhs = rhs);
Match /: Set[Match[lhs_], rhs_] :=
If[lhs === rhs, rhs,
Throw["mismatch: '" <> ToString[lhs] <> "'\[LongLeftRightArrow]'" <>
ToString[rhs] <> "'"]];
rhs_List] := (Match[lhs] = First@rhs;