MATHEMATICA ROGRAMMING

Rule Based Programming

Another definition for the factorial function:

fac[n_Integer]  :=  Infinity  /;  n  <  0

fac[-1]

fac[0]  =  1

fac[n_Integer]  :=  n * fac[n - 1]

fac[6]

Definition for the greatest common divisor:  the greatest common divisor d is the largest number that divides both a and b.   The definition below is based on a theorem in number theory which says, if for integer a,b,c such that |c| < b, and 
                      a = k b + c,
then gcd[a,b] = gcd[b,c].  Doing this (division) until remainder c becomes zero. This is called Euclidean algorithm.

gcd[a_,  0]  :=  a
gcd[a_,  b_] :=  gcd[b,  Mod[a, b]]

gcd[3, 6]

What about gcd[...] with one, three or more arguments?

Define our own differentiation algorithm

Let's agree that we do only partial differentiation, so that dif[expr, x] will be zero unless expr contains x explicitly.  To expression this fact, we can say:

dif[f_,  x_]  :=  0  /;  FreeQ[f, x]

dif[a, x]

We program in the linearity of differentiation:

dif[ f_  +  g_,  x_]  :=  dif[f, x]  +  dif[g, x]

dif[ a_ * g_,  x_]  :=  
      a * dif[g, x]  /;  FreeQ[a, x]

We know differential of polynomials (actually x^n).

dif[x, x]  :=  1

dif[x_^n_,  x_]  :=  
      n*x^(n - 1)  /;  (FreeQ[n, x])

Rule-Based Programming: operator overloading

Suppose we like to use the notation  S ∨ T to denote union of two sets S and T, and S ∧ T to mean the intersection of the two sets.  Since the two special symbol ∧ and ∨ is used for logical operations on the truth values True and False, can we use them for set operation?   We'll use a list to represent a set.

{a}  ∧  {a, b, c}

Since the operation is not defined, we get back the input.  Here is a definition that "overload" the operator ∧ and ∨.

Unprotect[And,  Or]

List[x___]  ∧  List[y___]  :=  
      Intersection[List[x], List[y]]

{a, b, c}  ∧  {a, e}

List[x___]  ∨  List[y___]  :=  
      Union[List[x],  List[y]]

{a, b, c}  ||  {a, e, r}

{a,  b}  &&  {}  ||  {c, d}