and thus spake Bill Rowe [2005.07.22 @ 01:35]:
> On 7/21/05 at 3:46 PM, dh at metrohm.ch (dh) wrote:
>
> >Hi, I seems to me that there is a bug in the implementation of pure
> >functions. If somebody can explain the following behaviour it would
> >be interessting. If not, maybe Wolfram can contribute something.
> >Consider f[x_]:= If[x==0,Return[Error],x]; f /@ {1,0} gives
> >{1,Error} what is fine. Now replace the function by a pure
> >function: If[#==0,Return[Error],#]& /@ {1,0} this gives
> >{1,Return["Error"]}. The Return statement has not been evaluated.
>
> Why do you want to use Return in this manner?
Often times in more complicated examples it is useful and efficient to
return from the function without continuing processing the rest of the
block of code. If you would like to do that in a pure function, I find
using Throw[] and Catch[] is a useful alternative:
Catch[
If[($Contents=Import[#])===$Failed,
Throw[$Failed],
doSomethingWith[$Contents]
]
]& /@ filenames
(note the subtle difference in functionality with the following:
Catch[
If[($Contents=Import[#])===$Failed,
Throw[$Failed],
doSomethingWith[$Contents]
]& /@ filenames;
]
)
More often than the simple switch above, the Throw/Catch approach makes
more since in complicated anonymous blocks of code like the following:
Catch[
Module[{$Contents,more,vars},
doSomeInitStuff[];
If[($Contents=Import[#])===$Failed,
Throw[$Failed],
doSomethingWith[$Contents]
];
doSomeMoreStuff[];
etc[]
]
]& /@ filenames
Note, you can still wrap Catch around the entire Map (/@) expression
to quit processing the entire loop on error as we did above in the
second example.
Happy Hacking!
--
/*------------------------------*\
| stephen layland |
| Documentation Programmer |
| http://members.wri.com/layland |
\*------------------------------*/