-1

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?

Chris
  • 26,361
  • 5
  • 21
  • 42
David 天宇 Wong
  • 3,724
  • 4
  • 35
  • 47

1 Answers1

7

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.

ivg
  • 34,431
  • 2
  • 35
  • 63
  • 2
    Generally speaking, if you're dealing with data structures that lend themselves to imperative programming, you're going to use an imperative loop. Arrays would be a good example. – Chris Jan 31 '22 at 23:12
  • If you are dealing with complex, recursive data structures.. Then use recursion and (if available) pattern matching. – G4143 Feb 01 '22 at 01:03