Print a List in OCaml

Print a List in OCaml

You should become familiar with the List.iter and functions. They are essential for programming in OCaml. If you also get comfortable with the Printf module, you can then write:

open Printf
let a = [1;2;3;4;5]
let () = List.iter (printf %d ) a

I open Printf in most of my code because I use the functions in it so often. Without that you would have to write Printf.printf in the last line. Also, if youre working in the toploop, dont forget to end the above statements with double semi-colons.

You can do this with a simple recursion :

let rec print_list = function 
[] -> ()
| e::l -> print_int e ; print_string   ; print_list l

The head of the list is printed, then you do a recursive call on the tail of the list.

Print a List in OCaml

print_string (String.concat   ( string_of_int list))

Leave a Reply

Your email address will not be published.