OCaml - List - Iterating through a list and displaying all elements inside

As you already saw it, creating a list in OCaml is not so difficult.
But this time, we will see how to iterate through a list and display all elements inside.

We will create two arrays, one of ints, the other of strings.
Once done, we will display their elements.
Let's see it with this OCaml list tutorial.  

Creating lists

List of ints:

#let number =  [1; 2; 3; 4];;

List of strings:

#let fruits =  ["apricot"; "raspberry"; "cherry"; "tomato"];;

Displaying elements of lists

List of strings:

(* PRINT LIST STRING *)
let rec print_list_string myList = match myList with
| [] -> print_endline "This is the end of the string list!"
| head::body -> 
begin
print_endline head;
print_list_string body
end
;;
 
List of ints:
 
(* PRINT LIST INT *)
let rec print_list_int myList = match myList with
| [] -> print_endline "This is the end of the int list!"
| head::body -> 
begin
print_int head; 
print_endline "";
print_list_int body
end
;;
OK, let's now display them with the two following functions:
 
# print_list_string fruits;; 
# print_list_int number;; 
Result:
apricot
raspberry
cherry
tomato
This is the end of the string list!
- : unit = ()
1
2
3
4
This is the end of the int list!
- : unit = ()

A great way to use OCaml for displaying lists! wink

 

 

Add new comment

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.