Re: A riddle: Functions that return unevaluated when they cannot
- To: mathgroup at smc.vnet.net
- Subject: [mg82703] Re: A riddle: Functions that return unevaluated when they cannot
- From: Szabolcs Horvát <szhorvat at gmail.com>
- Date: Mon, 29 Oct 2007 05:33:23 -0500 (EST)
- References: <ff9sin$5vc$1@smc.vnet.net> <ffckoe$sop$1@smc.vnet.net> <ffed3p$bg7$1@smc.vnet.net> <ffhqss$4mr$1@smc.vnet.net>
Albert wrote:
> Hi,
>
> Is this what you are looking for?
Yes, it it. Thank you! My newsreader has misplaced your message, so I
did not notice it until now.
A function like
g[x_] := Module[{res}, Pause[3]; res = x + 2; res /; res < 10]
reproduces the timing behaviour of Integrate[] et al. :-) I was not
familiar with this use of /; (it is described in the doc page of Module,
not in the doc page of Condition)
> In[27]:= ClearAll[g]
>
> In[28]:= g[x_]:=Module[{res=x+2},
> res/;res<10
> ]
>
> In[29]:= g[15]
> Out[29]= g[15]
>
> In[30]:= g[1]
> Out[30]= 3
>
> That is, using a conditional on your last expression decides whether or
> not a return value is returned or the input expression is returned
> unevaluated. This could of course be a flag which tells whether your
> calculation succeeded or not.
>
> I can't remember where I found this trick, I don't know whether it is
> documented and how/why it works. But I think it is used in the code of
> some of the Standard Packages (and probably in the functions you
> mentioned as well) so should work reliable, but I have no guarantees for
> that...
>
> hth,
>
> albert
>
--
Szabolcs