WOLFRAM LANGUAGE TUTORIAL

An Example: Defining Your Own Integration Function

Now that we have introduced the basic features of patterns in the Wolfram Language, 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 the Wolfram Language.

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 the Wolfram Language.

mathematical formWolfram Language definition
integrate[y_+z_,x_]:=integrate[y,x]+integrate[z,x]
( independent of )integrate[c_y_,x_]:=c integrate[y,x]/;FreeQ[c,x]
integrate[c_,x_]:=cx/;FreeQ[c,x]
, integrate[x_^n_.,x_]:=x^(n+1)/(n+1)/;FreeQ[n,x]&&n!=-1
integrate[1/(a_.x_+b_.),x_]:=Log[ax+b]/a/;FreeQ[{a,b},x]
integrate[Exp[a_.x_+b_.],x_]:=Exp[ax+b]/a/;FreeQ[{a,b},x]

Definitions for an integration function.

This implements the linearity relation for integrals: .
In[1]:=
Click for copyable input
The associativity of Plus makes the linearity relation work with any number of terms in the sum.
In[2]:=
Click for copyable input
Out[2]=
This makes pull out factors that are independent of the integration variable .
In[3]:=
Click for copyable input
The Wolfram Language tests each term in each product to see whether it satisfies the FreeQ condition, and so can be pulled out.
In[4]:=
Click for copyable input
Out[4]=
This gives the integral of a constant.
In[5]:=
Click for copyable input
Now the constant term in the sum can be integrated.
In[6]:=
Click for copyable input
Out[6]=
This gives the standard formula for the integral of . By using the pattern , rather than , we include the case of .
In[7]:=
Click for copyable input
Now this integral can be done completely.
In[8]:=
Click for copyable input
Out[8]=
Of course, the builtin integration function Integrate (with a capital I) could have done the integral anyway.
In[9]:=
Click for copyable input
Out[9]=
Here is the rule for integrating the reciprocal of a linear function. The pattern stands for any linear function of .
In[10]:=
Click for copyable input
Here both and take on their default values.
In[11]:=
Click for copyable input
Out[11]=
Here is a more complicated case. The symbol now matches .
In[12]:=
Click for copyable input
Out[12]=
You can go on and add many more rules for integration. Here is a rule for integrating exponentials.
In[13]:=
Click for copyable input