MathGroup Archive 2010

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

Search the Archive

Re: How to short-circuit match failure?

  • To: mathgroup at
  • Subject: [mg114497] Re: How to short-circuit match failure?
  • From: kj < at>
  • Date: Sun, 5 Dec 2010 21:56:43 -0500 (EST)
  • References: <ictfq8$mck$> <id01ld$h6o$> <id4sku$cge$>

In <id4sku$cge$1 at> kj < at> writes:

>foo::toolong = "First argument is too long";
>foo::nolist = "First argument is not a list";
>foo::nargs = "foo called with `1` argument(s); 2 expected";
>foo[args___] := Module[{chkargs, argsok, core, othervars},
>  chkargs[x_List /; Length[x] < 3, y_] := True;
>  chkargs[_List, _] := Message[foo::toolong]; 
>  chkargs[_, _] := Message[foo::nolist]; 
>  chkargs[x___] := Message[foo::nargs, Length[{x}]];
>  core[x_, y_] := {#, y} & /@ x;
>  argsok = chkargs[args];
>  argsok && core[args] /; argsok
>  ]

Actually, there's an unexpected problem with this solution.  As I
reported in a different thread (Message-ID:  <idd7ml$nae$1 at>,
Subject: [mg114497] Tempvar zombies littering my context!), each evalution of
foo[...] would lead to the addition of lingering "temporary"
variables to the context.  Therefore, if a function defined as
proposed above was called many times (e.g. in a loop with many
iterations), this would lead to an explosion in the number of
variables that would have to be kept track of in the context.

One workaround is to change Module to Block, since Block does not
create any temporary variables in the first place.  Of course,
using Block is trickier than using Module, because there's the risk
that a block variable will localize the value of a *global* variable
that is used by some other function invoked during the evaluation
of the Block.  (There may be a way to use Unique in a way that
automatically prevents this problem with Block without requiring
any particular care from the programmer, but, if so, it is beyond
my Mathematica skill to devise it.)


  • Prev by Date: Re: How to get the Inverse matrix in symbolic way?
  • Next by Date: Re: Cyclical Decimal Expansion
  • Previous by thread: Re: How to short-circuit match failure?
  • Next by thread: Re: How to short-circuit match failure?