MathGroup Archive 2005

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

Search the Archive

Re: Re: Returnin pure function

  • To: mathgroup at smc.vnet.net
  • Subject: [mg58911] Re: [mg58887] Re: Returnin pure function
  • From: stephen layland <layland at wolfram.com>
  • Date: Sat, 23 Jul 2005 05:32:25 -0400 (EDT)
  • References: <200507220558.BAA06924@smc.vnet.net>
  • Sender: owner-wri-mathgroup at wolfram.com

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 |
\*------------------------------*/


  • Prev by Date: Re: an Integrate question
  • Next by Date: Re: Returnin pure function
  • Previous by thread: Re: Returnin pure function
  • Next by thread: Re: Returnin pure function