MathGroup Archive 2005

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

Search the Archive

Re: Re: Best construct for control structure

  • To: mathgroup at
  • Subject: [mg60088] Re: [mg60070] Re: Best construct for control structure
  • From: "E. Martin-Serrano" <EmilioMartin-Serrano at>
  • Date: Thu, 1 Sep 2005 06:43:19 -0400 (EDT)
  • Sender: owner-wri-mathgroup at

Maybe you are looking for this (from Maeders' Programming in Mathematica)

Attributes[Until] = {HoldAll}
Until[body_, test_] := Module[ {t}, For[ t=False, !t, t=test, body ] ]

E. martin-Serrano

-----Original Message-----
From: Carl K. Woll [mailto:carlw at] 
To: mathgroup at
Subject: [mg60088] [mg60070] Re: Best construct for control structure

"Usenet poster" wrote:
> Dear Mathematica gurus,
> I'm trying to learn the right way to code a homebrew control structure. As

> a
> example, I've tried coding the following (of course, a For could also do
> it):
> In[77]:=
> myRepeat[expr_,cond_]:=(ReleaseHold[expr];
>    While[ReleaseHold[cond],ReleaseHold[expr]])
> Attributes[myRepeat]={HoldAll};
> In[79]:=
> x=0;
> Trace[myRepeat[x++,x<2]]
> x
> Out[80]=
> {myRepeat[x++,x<2],ReleaseHold[x++];
>  While[ReleaseHold[x<2],ReleaseHold[x++]],{{x++,{x,0},{x=1,1},0},
>    ReleaseHold[0],
>    0},{While[ReleaseHold[x<2],ReleaseHold[x++]],{{{x,1},1<2,True},
>      ReleaseHold[True],True},{{x++,{x,1},{x=2,2},1},ReleaseHold[1],
>      1},{{{x,2},2<2,False},ReleaseHold[False],False},Null},Null}
> Out[81]=
> 2
> While (pun intended) the result is indeed correct as the trace shows, I
> wonder if there isn't a much better way to have cond and expr somehow hold
> without having to call ReleaseHold that much times. I may be completely
> misguided, but I see this as a inelegant inefficency.

There is no reason to use ReleaseHold in your code. Simply remove all of 
them, and everythings works fine. As an alternative, you may just use the 
single argument form of While:

SetAttributes[repeat, HoldAll]
repeat[expr_, cond_] := While[expr; cond]

For your example we have:




> Or, are Mathematica control structures (For, While, ...) totally
> different from other
> functions, inherently, that we just can't think about building ours
> (efficiently and robustly, I mean).
> -- 
> You        usenet
> can              at
> reach              q-e-d
> me                      dot
> here                       org

Carl Woll
Wolfram Research 

  • Prev by Date: Re: Keyboard problems - no "dead keys" - in Linux version of Mathematica
  • Next by Date: Re: How to assembly a stiffness matrix ?
  • Previous by thread: Re: Best construct for control structure
  • Next by thread: MakeBoxes vs Format