In this shot, we'll learn how to get the head of the list (first item in the list) without iterating through the list. We'll use the List.hd
method in Ocaml to achieve this.
List.hd[listitems]
The List.hd
method receives the list of which the first item we want to retrieve as a parameter.
The List.hd
method returns the first item in the list.
Let's look at the code below:
let x = [3; 2; 5];;print_int(List.hd x)
In the code snippet above:
x
with list items [3;2;5]
. List.hd
method to get the head of the list x
and then use the print_int()
method to print the head item to the console.