Re: Proper style for argument checking?
- To: mathgroup at smc.vnet.net
- Subject: [mg111980] Re: Proper style for argument checking?
- From: David Bailey <dave at removedbailey.co.uk>
- Date: Mon, 23 Aug 2010 02:38:21 -0400 (EDT)
- References: <i4o25b$akh$1@smc.vnet.net>
On 21/08/10 09:18, James Stein wrote: > I use this cell in my notebooks: > > ClearAll[abort, abortLog, fail, failLog]; > abortLog = failLog = {}; > abort[s__] := (Beep[]; > AppendTo[abortLog, {s}]; > Print["Aborting: ", s]; > Abort[]); > fail[s__] := (Beep[]; > AppendTo[failLog, {s}]; > Print["Fail: ", s] > ); > > Neither abort' nor 'fail' does exactly what you request, but why > return the function unevaluated in case of failure? My preference is > either to abort on failure (normal case) or report and continue > (regression testing). In my experience, a function that returns > unevaluated merely wreaks havoc higher in the calling chain. > > I'm eager to hear other responses to your query. > > > On Fri, Aug 20, 2010 at 4:06 AM, Yaroslav Bulatov<yaroslavvb at gmail.com> wrote: >> I have a function, and I'd like to do several checks on arguments >> before evaluating it. If some check fails, I want the function to >> return unevaluated and print corresponding error message, what's the >> proper style of doing it? >> >> Help for "Message" gives an example for a single check, but it seems >> awkward to use same form for multiple checks. >> >> > The easiest way to write a function that fails by returning unevaluated, is to either add conditions to the individual arguments, or to write a condition at the end of the definition: In[1]:= foo[x_] := Module[{y = x^2}, y] /; x > 0; In[2]:= foo[3] Out[2]= 9 In[3]:= foo[-1] Out[3]= foo[-1] You can include a call to Message inside the test, if you wish. As to whether this is a useful way for a function to behave - it obviously depends on what the function does, and what it is for! Those Mathematica functions that return unevaluated - e.g. Integrate - seem to be maths procedures, where the system may simply 'not know' how to do something, or where subsequent definitions may make an evaluation possible in the future. If you expect a function might return unevaluated, why not check its Head to see if it is, say, Integrate, and then do whatever is appropriate? David Bailey http://www.dbaileyconsultancy.co.uk