This is documentation for Mathematica 3, which was
based on an earlier version of the Wolfram Language.
View current documentation (Version 11.1)
 Documentation / Mathematica / The Mathematica Book / Principles of Mathematica / Patterns  /

2.3.14 An Example: Defining Your Own Integration Function

Now that we have introduced the basic features of patterns in Mathematica, we can use them to give a more or less complete example. We will show how you could define your own simple integration function in Mathematica.
From a mathematical point of view, the integration function is defined by a sequence of mathematical relations. By setting up transformation rules for patterns, you can implement these mathematical relations quite directly in Mathematica.

Definitions for an integration function.

  • This implements the linearity relation for integrals:

  • In[1]:= integrate[y_ + z_, x_] :=
    integrate[y, x] + integrate[z, x]

  • The associativity of Plus makes the linearity relation work with any number of terms in the sum.
  • In[2]:= integrate[a x + b x^2 + 3, x]


  • This makes integrate pull out factors that are independent of the integration variable x.
  • In[3]:= integrate[c_ y_, x_] := c integrate[y, x] /; FreeQ[c, x]

  • Mathematica tests each term in each product to see whether it satisfies the FreeQ condition, and so can be pulled out.
  • In[4]:= integrate[a x + b x^2 + 3, x]


  • This gives the integral

    of a constant.
  • In[5]:= integrate[c_, x_] := c x /; FreeQ[c, x]

  • Now the constant term in the sum can be integrated.
  • In[6]:= integrate[a x + b x^2 + 3, x]


  • This gives the standard formula for the integral of . By using the pattern x_^n_., rather than x_^n_, we include the case of

  • In[7]:= integrate[x_^n_., x_] :=
    x^(n+1)/(n+1) /; FreeQ[n, x] && n != -1

  • Now this integral can be done completely.
  • In[8]:= integrate[a x + b x^2 + 3, x]


  • Of course, the built-in integration function Integrate (with a capital I) could have done the integral anyway.
  • In[9]:= Integrate[a x + b x^2 + 3, x]


  • Here is the rule for integrating the reciprocal of a linear function. The pattern a_.x_+b_. stands for any linear function of x.
  • In[10]:= integrate[1/(a_. x_ + b_.), x_] :=
    Log[a x + b]/a /; FreeQ[{a,b}, x]

  • Here both a and b take on their default values.
  • In[11]:= integrate[1/x, x]


  • Here is a more complicated case. The symbol a now matches 2p.
  • In[12]:= integrate[1/(2 p x - 1), x]


  • You can go on and add many more rules for integration. Here is a rule for integrating exponentials.
  • In[13]:= integrate[Exp[a_. x_ + b_.], x_] :=
    Exp[a x + b]/a /; FreeQ[{a,b}, x]