Wolfram ResearchPRODUCTSPURCHASEFOR USERSCOMPANYOUR SITES
THIS IS DOCUMENTATION FOR AN OBSOLETE PRODUCT.
SEE THE DOCUMENTATION CENTER FOR THE LATEST INFORMATION.
Previous section-----Next section

2.3.4 Specifying Types of Expression in Patterns

You can tell a lot about what "type" of expression something is by looking at its head. Thus, for example, an integer has head Integer, while a list has head List.

In a pattern, _h and x_h represent expressions that are constrained to have head h. Thus, for example, _Integer represents any integer, while _List represents any list.

x_h an expression with head h
x_Integer an integer
x_Real an approximate real number
x_Complex a complex number
x_List a list
x_Symbol a symbol

Patterns for objects with specified heads.
This replaces just those elements that are integers.

In[1]:=  {a, 4, 5, b} /. x_Integer -> p[x]

Out[1]=

You can think of making an assignment for f[x_Integer] as like defining a function f that must take an argument of "type" Integer.

This defines a value for the function gamma when its argument is an integer.

In[2]:=  gamma[n_Integer] := (n - 1)!

The definition applies only when the argument of gamma is an integer.

In[3]:=  gamma[4] + gamma[x]

Out[3]=

The object 4. has head Real, so the definition does not apply.

In[4]:=  gamma[4.]

Out[4]=

This defines values for expressions with integer exponents.

In[5]:=  d[x_^n_Integer] := n x^(n-1)

The definition is used only when the exponent is an integer.

In[6]:=  d[x^4] + d[(a+b)^3] + d[x^(1/2)]

Out[6]=


Any questions about topics on this page? Click here to get an individual response.Buy NowFree TrialMore Information



 © 2009 Wolfram Research, Inc.  Terms of Use  Privacy Policy |
Sign up for our newsletter: