Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print a List in OCaml

Tags:

ocaml

I want to do something as simple as this:

Print a list.

let a = [1;2;3;4;5] 

How can I print this list to Standard Output?

like image 912
Gitmo Avatar asked Feb 03 '12 20:02

Gitmo


People also ask

What is a list in OCaml?

A list is an ordered sequence of elements. All elements of a list in OCaml must be the same type. Lists are built into the language and have a special syntax. Here is a list of three integers: # [1; 2; 3];; - : int list = [1; 2; 3] Note semicolons separate the elements, not commas.

What does :: do in OCaml?

Regarding the :: symbol - as already mentioned, it is used to create lists from a single element and a list ( 1::[2;3] creates a list [1;2;3] ).


1 Answers

You should become familiar with the List.iter and List.map 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 you're working in the toploop, don't forget to end the above statements with double semi-colons.

like image 190
Ashish Agarwal Avatar answered Oct 08 '22 14:10

Ashish Agarwal