recursion in Mathematica

I have been playing with creating pseudotexts via markov chains recently, and may post some code soon. Creating random text via markov chains has two steps — first you analyze the source material and make a tree that describes the likelihood of different words following each other, and second you create a random walk through that tree, respecting the relative probability of the different paths.

The first step is easily done via many different methods, but if you want a tree of arbitrary depth, it becomes most elegant to use recursion. This is no harder in Mathematica than any other language, and for the sake of any novices googling around for examples of using Mathematica recursively, note the following example —

If you want to compute factorials, in practice you would probably use Mathematica’s postfix operator, !

In[1]:= 4!
Out[1]= 24

You could program your own version about a thousand different ways. I find this to be natural:

In[2]:= functionalFactorial[x_] := Apply[Times, Range[x]]
In[3]:= functionalFactorial[4]
Out[3]= 24

And if you wanted a recursive version, you could do

In[4]:= recursiveFactorial[x_] := If[x == 1, 1, x*recursiveFactorial[x - 1]]
In[5]:= recursiveFactorial[4]
Out[5]= 24

As in any recursive code, you need a test in the inner loop that defines at least one stopping point (in this case when we're multiplying by 1). Without that branch, all recursions would continue indefinitely.

Either of the user-defined functions above could be compiled for additional speed.