Recursion in OCaml
Our example demonstrates recursive functions in OCaml. Here’s a classic example.
In OCaml, we use the let rec
keyword to define recursive functions. The fact
function demonstrates a simple recursive implementation of factorial calculation.
For the Fibonacci sequence, we define another recursive function fib
. In OCaml, we don’t need to declare the function type explicitly before defining it, as the language has powerful type inference.
To run this program, save it as recursion.ml
and use the OCaml compiler:
The output shows the factorial of 7 (5040) and the 7th Fibonacci number (13).
OCaml’s pattern matching and tail-call optimization make it particularly well-suited for recursive algorithms, often resulting in efficient and readable code.