简体   繁体   中英

OCaml loops: imperative vs recursion

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 (ie, 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM