       Re: Loop problem

• To: mathgroup at yoda.physics.unc.edu
• Subject: Re: Loop problem
• From: withoff
• Date: Thu, 8 Oct 92 10:47:37 CDT

```> I'm having no luck getting either Break[] or Return[] to get me out
> of a loop.  I have an iterating procedure in which values at each
> step are computed from values at the previous step.  If the new
> values ever fail one of several tests, I want a message printed and
> the loop to terminate.  So I embedded several If[test,Break[]]
> statements in my loop.  When one of the tests fails, however, the
> message prints but the loop does not terminate; rather, it seems to
> go to the next step (ie, the behavior I expect of Continue[]).
>
> Any ideas/suggestions?
>
> Here's the code:
>
> s = 1;
> l = 1;
> For[t = 0,t < n,t++;
>	{
>	a[t] = f[s[t],l[t]];
>	If[g[s[t],l[t]] <= 0,Return[Print["g[] < 0"]]];
>	l[t+1] = h[a[t],s[t],l[t]];
>	If[l[t+1] <= 0.05,Return[Print["l <= 0.05"]]];
>	If[l[t+1] > 25,Return[Print["l > 25"]]];
>	sss[t+1] = j[a[t],s[t],l[t]];
>	Print[t," s = ",s[t]," lambda = ",l[t]]
>	}]
>
> Any assistance would be greatly appreciated.
>
> ---
> -
> Stefano Pagiola
> Food Research Institute, Stanford University
> spagiola at frinext.stanford.edu (NeXTMail encouraged)
> spagiola at FRI-nxt-Pagiola.stanford.edu (NeXTMail encouraged)

One problem is the extra set of curly braces, {...}, around the
last argument in For.  The For statment will Return if the body
evaluates to something with a head of Return.  In this program,
however, it will evaluate to something with a head of List:

In:= If[True, Return[finished]]

Out= Return[finished]

In:= { If[True, Return[finished]] }

Out= {Return[finished]}

In:= FullForm[%]

Out//FullForm= List[Return[finished]]

Also, in the first line of the program (For[t = 0,t < n,t++;) I suspect
that the final semicolon should be a comma.

If you need to "return" from somewhere nested inside an expression,
such as inside an extra set of curly braces, you can use Throw and Catch,
which behave in some respects similar to "return" in C:

In:= Catch[
For[t = 1, True, t++,
{
Print["t = ", t];
If[t > 5, Throw[t] ]
}
]
]
t = 1
t = 2
t = 3
t = 4
t = 5
t = 6

Out= 6

Although this example with the extra curly braces {...} around the
body is contrived for purposes of illustration, there are plenty
of realistic situations in which Throw and Catch are necessary.

Dave Withoff
withoff at wri.com

```

• Prev by Date: Re: ReplaceAll feature
• Next by Date: Re: A Simplify that really simplifies? Summary
• Previous by thread: Loop problem
• Next by thread: Re: Loop problem