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
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:
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)
)