Re: Validating functions input

*To*: mathgroup at smc.vnet.net*Subject*: [mg58799] Re: Validating functions input*From*: Peter Pein <petsie at dordos.net>*Date*: Tue, 19 Jul 2005 04:10:07 -0400 (EDT)*References*: <dbflkk$n0p$1@smc.vnet.net>*Sender*: owner-wri-mathgroup at wolfram.com

Nilton schrieb: > I have a function that must have its input validated. > > f[x,y] > > I want to validate if x <= 2^y. If it's valid, then just return the > symbol f[x,y] unevaluated. If it's not valid, I want to return some > symbol, Null for instance, and issue an error message. > > The following is a try, but it doesn't work, because it's definition is > recursive: > > f::invalid = "Invalid arguments" > f[x_,y_] := If[x <= 2^y, f[x,y], Message[f::invalid]] > > Is there any way to implement this? > > Thanks, > -- Nilton > Hi Nilton, restrict the definition to invalid cases and let f simply print the error message: In[1]:= Clear[f]; f::invalid = "Invalid arguments `1` > `2`"; f[x_, y_] /; x > 2^y := Message[f::invalid, x, 2^y] Since f doesn't know what to do with x<=2^y, it returns unevaluated: In[4]:= f[1, 1] Out[4]= f[1, 1] and prints the message otherwise: In[5]:= f[3, 1] From In[5]:= f::invalid: Invalid arguments 3 > 2 but this version can not handle (most) symbolic expressions: In[6]:= Simplify[f[2^n + 1, n]] Out[6]= f[1 + 2^n, n] If we re-define f as In[7]:= f[x_, y_] /; Simplify[x > 2^y] := Message[f::invalid, x, 2^y] then In[8]:= f[1 + 2^n, n] acts as desired From In[8]:= f::invalid: Invalid arguments 1 + 2^n > 2^n but this might take some time when x and/or y are large expressions. -- Peter Pein Berlin http://people.freenet.de/Peter_Berlin/