MathGroup Archive 2000

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

Search the Archive

Re: A simple programming question.

  • To: mathgroup at
  • Subject: [mg23184] Re: [mg23174] A simple programming question.
  • From: Preston Nichols <pnichols at>
  • Date: Mon, 24 Apr 2000 01:11:56 -0400 (EDT)
  • Sender: owner-wri-mathgroup at

At 11:48 PM 04/20/2000 -0400, Jack Goldberg wrote:
>Hi group;
>In a post by Russell Towle [mg23117] appears a short 
>program written by David Park from an idea of Carl Woll.
>Here it is:
>OrderedUnion2[li_] :=
>	Block[ {i},
>		i[n_] := (i[n] = Null; n);
>		i /@ li
>	]
>I understand about 98% of what's going on, but one item
>keeps eluding me.  What is the role of the parentheses in 
>the first line of the Block?  

The parentheses serve to keep both the assignment i[n] = Null and the
evaluation of n itself within the definition of i[n_] (or actually, within
the scope of the :=).  The effect is that evaluation of i[n] returns just n
(from the last n before the closing parenthesis), UNLESS i[n] already has a
value, such as Null.  If i[n] (for some particular n) is evaluated after a
value for it has already been Set (by  evaluation of =), then the
SetDelayed (i.e. :=) is not used at all; the previously existing value of
i[n] (namely Null) is returned.  (And that's why values of i must be

>A second related question.  In order to understand the 
>"inner workings" I used Trace to no avail; I looked up 
>CompoundExpression to no avail; I tried Print[] at 
>various spots, also to no avail.  Can anyone recommend
>a scheme that could have helped me understand what was 
>going on?  

I can suggest, if not necessarily recommend, use of FullForm assisted by
HoldForm.  Try wrapping the Block structure in HoldForm[FullForm[ ]], with
and without the parentheses:

   Block[ {i},
      i[n_] := (i[n] = Null; n);
      i /@ li

      SetDelayed[i[Pattern[n, Blank[]]], 
        CompoundExpression[Set[i[n], Null], n]], Map[i, li]]]

   Block[ {i},
      i[n_] := (i[n] = Null; n);
      i /@ li

    CompoundExpression[SetDelayed[i[Pattern[n, Blank[]]], Set[i[n], Null]], n,
       Map[i, li]]]

Without the parentheses, there is only one CompoundExpression, which is the
(whole) "body" of the Block.  With the parentheses present, there are
nested CompoundExpression's, the inner one appearing as the second argument
of SetDelayed and made up of exactly the contents of the parentheses.
Judge for yourself whether this might have provided you the necessary clue.

I hope that helps a little.

Preston Nichols
Mathematics and Computer Science
Wittenberg University

>Someone care to guide me here?  Thanks,

  • Prev by Date: Re: Help, my MathLink Examples segfault.
  • Next by Date: Re: Help, my MathLink Examples segfault.
  • Previous by thread: Re: Re: A simple programming question.
  • Next by thread: RE: A simple programming question.