What is the List.hd method in Ocaml?
Overview
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.
Syntax
List.hd[listitems]
Syntax for the List.hd method
Parameters
The List.hd method receives the list of which the first item we want to retrieve as a parameter.
Return value
The List.hd method returns the first item in the list.
Example
Let's look at the code below:
let x = [3; 2; 5];;print_int(List.hd x)
Explanation
In the code snippet above:
- Line 1: We create a list
xwith list items[3;2;5].
- Line 2: We use the
List.hdmethod to get the head of the listxand then use theprint_int()method to print the head item to the console.