Recursion by Rule

How to do recursion by using Rule ?

Simple way.

Example :

   fact = x_ /; x > 1 :> x ((x - 1) /. fact);
 
  fib = x_ /; x > 1 :> ( (x - 1) /. fib) + ((x - 2) /. fib);

8 /. fib

21

6 /.fact 

120

Looks cool.

But

fact = x_ /; x > 1 :> x ((x - 1) /. fact);

and

In[132]:= 0 /. fact

Out[132]= 0

when ( mathmatically correct ! )

In[134]:= 0!

Out[134]= 1
2 Likes

Thanks, Hans Dolhaine for Hint.

The correct Rule:

fact = x_ :> If[x == 1!! x == 0, 1, x ((x - 1) /. fact)];

Sounds good. But what is the role of Factorial2? Shouldn’t it be

fact = x_ :> If[x == 1 || x == 0, 1, x ((x - 1) /. fact)];
1 Like

the rule of Factorial2

 fact = x_Integer :> If[x == 1 || x == 0, 1, x ((x - 2) /. fact)];

small test

Range[10] /. fact
{1, 2, 3, 8, 15, 48, 105, 384, 945, 3840}