MathGroup Archive 2005

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

Search the Archive

Re: Validating functions input

  • To: mathgroup at
  • Subject: [mg58799] Re: Validating functions input
  • From: Peter Pein <petsie at>
  • Date: Tue, 19 Jul 2005 04:10:07 -0400 (EDT)
  • References: <dbflkk$n0p$>
  • Sender: owner-wri-mathgroup at

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]


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

  • Prev by Date: Re: Directed Graph from Adjacency Matrix
  • Next by Date: Re: "2p" in BenchmarkReport[] ?
  • Previous by thread: Re: Validating functions input
  • Next by thread: "2p" in BenchmarkReport[] ?