MathGroup Archive 2008

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

Search the Archive

Re: simple pattern match question

  • To: mathgroup at
  • Subject: [mg91178] Re: simple pattern match question
  • From: Jean-Marc Gulliet <jeanmarc.gulliet at>
  • Date: Fri, 8 Aug 2008 07:16:12 -0400 (EDT)
  • Organization: The Open University, Milton Keynes, UK
  • References: <g7ed78$2po$>

congruentialuminaire at wrote:

> I am trying to understand simple pattern rule evaulation. The
> following trivial examples baffles me:
> ---------------------------------------------------
> In[1]:= f[x_Number] := x ^ 2
> In[2]:= f[3]
> Out[2]= f[3]
> In[3]:= f[3.3]
> Out[3]= f[3.3]
> In[4]:= NumberQ[3.3]
> Out[4]= True
> --------------------------------------------------
> Why is it that f[3.3] does not evaluate??

The pattern x_Number matches any expression with head Number.

The head Number does not exist natively in Mathematica.

The numbers 3 and 3.3 have head Integer and Real, respectively.

   In[1]:= Head[3]

   Out[1]= Integer

   Out[2]= Real

So, except if you define some expression with head Number, the 
definition of the function f will match nothing and the function f will 
return unevaluated in all cases.

The pattern x_?NumberQ tests whether the expression x is a number, that 
is if upon evaluation the resulting expression has head Integer, 
Rational, Real, or Complex. (Note that Number[Pi] failed.)

The pattern x_?NumericQ test whether the expression x can be evaluated 
to a numeric quantity. (NumericQ[Pi] returns True.)

   In[3]:= f[x_?NumberQ] := x^2

   Out[4]= 9

   Out[5]= 10.89

-- Jean-Marc

  • Prev by Date: Purchasing Mathematica
  • Next by Date: Re: Mathematica and Mathieu DEQ Results?
  • Previous by thread: Re: simple pattern match question
  • Next by thread: Multiplying a vector over multiple vectors