# 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:= 4! Out= 24 ```

``` You could program your own version about a thousand different ways. I find this to be natural: In:= functionalFactorial[x_] := Apply[Times, Range[x]] In:= functionalFactorial Out= 24 And if you wanted a recursive version, you could do In:= recursiveFactorial[x_] := If[x == 1, 1, x*recursiveFactorial[x - 1]] In:= recursiveFactorial Out= 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. ```
``` This entry was posted in mathematica on October 9, 2010 by stern. ```
``` Post navigation ← Mean Girls Pamela writes about a dog lady → ```