Re: Help with functions

• To: mathgroup at smc.vnet.net
• Subject: [mg65645] Re: [mg65612] Help with functions
• From: Andrzej Kozlowski <akoz at mimuw.edu.pl>
• Date: Wed, 12 Apr 2006 05:59:55 -0400 (EDT)
• References: <200604110804.EAA11186@smc.vnet.net>
• Sender: owner-wri-mathgroup at wolfram.com

```On 11 Apr 2006, at 17:04, IronBone wrote:

> I have written a simmple function which (in my opinion) should always
> return False. But it returns True.
>
> It seems that Return[False] breaks the Do loop but not returns from
> the
> function.
> I thing I don't understand,  what is defining of functions. Can
> somebody
> explain me this.
>
> fun[x_] := Module[{i},
>      Do[If[i == 2, Return[False]], {i, 5}];
>      Return[True];
>      ]
>
>

You need a double Return in the case of a DO loop:

fun[] := Module[{i},
Do[If[i == 2, Return[Return[False]]], {i, 5}];
True;
]

fun[]

False

A single Return will work in the case of a While loop.

fun1[] := Module[{i = 1}, While[i < Infinity, i++; If[PrimeQ[i],
Return[i]]]]

fun1[]

2

The reason for this different behaviour is that Do and While loops
are used for different purposes and both kinds of behaviour can be
convenient. But in general it is much better to use Throw and Catch;
you never really  need to use Return in Mathematica.

(And Return[True] at the end of your code is probably borrowed from
another language like Fortran or C; it is not needed in Mathematica
and only makes the code look unnecessarily cluttered).

Andrzej Kozlowski
Tokyo, Japan

```

• Prev by Date: Re: Integral problem
• Next by Date: FindFit / NonlinearFit Problems
• Previous by thread: Help with functions
• Next by thread: Re: Help with functions