Re: Best construct for control structure

• To: mathgroup at smc.vnet.net
• Subject: [mg60070] Re: Best construct for control structure
• From: "Carl K. Woll" <carlw at u.washington.edu>
• Date: Thu, 1 Sep 2005 02:13:07 -0400 (EDT)
• Organization: University of Washington
• References: <df3bsl\$kpd\$1@smc.vnet.net>
• Sender: owner-wri-mathgroup at wolfram.com

```"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:

In[5]:=
x=0;

In[6]:=
repeat[x++,x<2]//Trace
Out[6]=
{repeat[x++,x<2],
While[x++;x<2],{x++;x<2,{x++,{x,0},{x=1,1},0},{{x,1},1<2,True},True},{x++;
x<2,{x++,{x,1},{x=2,2},1},{{x,2},2<2,False},False},Null}

In[7]:=
x
Out[7]=
2

> 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: Trig functions expressed as Radicals
• Next by Date: MakeBoxes vs Format
• Previous by thread: Re: Trig functions expressed as Radicals
• Next by thread: Re: Re: Best construct for control structure