I just stumbled upon some OCaml code that writes a loop like this:
let r = ref (f 0) in
for i = 1 to k - 1 do
r := f i * !r
done ;
!r
in
Which is interesting as I normally see this done using recursive functions in OCaml usually. Is there an advantage to one versus the other?
It is a matter of style nothing more. OCaml enables both pure functional and pure imperative style and lets the users choose what suits their needs.
In this particular example, the same implementation that uses the recursive function will have the same performance (and basically will be compiled to the same code). In more complex examples, when the reference is storing not an immediate object (i.e., when it is stored in the heap), the imperative loop might be slower than a pure recursive function as the former will involve a write barrier on each update.