MathGroup Archive 2008

[Date Index] [Thread Index] [Author Index]

Search the Archive

"matched" Set[]

I have used Erlang ( 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
something else, such as {badarg, wrong}. Now, "badarg" cannot be
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] <> "'"]];
Match /: Set[Match[lhs_, lhs2_, padding__],
   rhs_List] := (Match[lhs] = First@rhs;
   Match[lhs2, padding] = Rest@rhs);
Match /: Set[
   Match[lhs1_, lhs2_], {rhs1_, rhs2_}] := (Match[lhs1] = rhs1;
   Match[lhs2] = rhs2);

Li Zhengji

  • Prev by Date: Monitoring/collecting evaluations
  • Next by Date: Help on Collecting Integers
  • Previous by thread: Monitoring/collecting evaluations
  • Next by thread: Help on Collecting Integers