What is List.nth method in Ocaml?
Overview
In this shot, we'll learn how to use the List.nth method to get a specific element in the nth index.
It becomes hard to reach a particular element in a list by iterating the whole list from the start to that element. The easier way is to directly jump to the index of the required element.
The List.nth method
The List.nth method is used to get an element from a list at the nth index. Always remember, the index of the list always starts from 0. For example, if we need to reach the third element of the list, we will provide an index as 2.
Syntax
List.nth myList index
Syntax for the List.nth method
Parameters
The List.nth method receives a list we want to work with and the index of the element as parameters.
Return value
It returns the value of the element at the provided index in the provided list.
Code example
Let's look at the code below:
let myList = [4;5;6;7;2];;let myElement = List.nth myList 2;;print_int(myElement)
Explanation
- Line 1: We create our list and save it as
myList.
- Line 2: We use the
List.nthmethod to get the second element of the listmyListand save it in a variablemyElement.
- Line 3: We print it to the screen,
print_int(myElement).