Search code examples
ocaml

Does OCaml support for-each loops?


I would like to print each integer in a list.

I can do this with List.iter like so:

digits
|> List.iter
  (fun i -> print_int i; print_newline ())

However, I generally prefer to keep imperative code outside of pipelines of functions.

Is it possible to write this in a for-each loop in OCaml?

(Hypothetical syntax)

for i in digits do
  print_int i ; 
  print_newline ()
end

Solution

  • Short answer? No.

    Longer answer: In the bygone days of camlp4, something like this probably could have been hacked together.

    A few questions we'd have to answer if we were going to add this syntax and the accompanying semantics:

    • What does this syntax semantically map to? How do we make this work for any collection of things? Can we even do that? Do we just have it iterate over something like a sequence?
    • If we can solve the above, if we iterate over a mutable collection, how does mutating that collection within the loop affect iteration? This is a major source of errors a in other languages with this type of construct.
    • If we get past that, how is this better than what we have?

    Suggestion: Simplify your shown code by using the Printf or Format modules and partial application.

    digits
    |> List.iter (Format.printf "%d\n")
    

    Alternatively, you can use Format.pp_print_list to treat the entire list as a single thing to be printed.

    digits
    |> Format.(
         printf 
         "%a\n" 
         (pp_print_list ~pp_sep: pp_print_newline pp_print_int) 
       )