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_han expression with head h
x_Integeran integer
x_Realan approximate real number
x_Complexa complex number
x_Lista list
x_Symbola symbol

Patterns for objects with specified heads.

This replaces just those elements that are integers.
Click for copyable input

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.
Click for copyable input
The definition applies only when the argument of gamma is an integer.
Click for copyable input
The object 4. has head Real, so the definition does not apply.
Click for copyable input
This defines values for expressions with integer exponents.
Click for copyable input
The definition is used only when the exponent is an integer.
Click for copyable input

Related Tutorials