Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

ocaml
communitycreator

What is List.nth method in Ocaml?

Chinweuba Elijah Azubuike

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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)
Using the List.nth method

Explanation

  • Line 1: We create our list and save it as myList.
  • Line 2: We use the List.nth method to get the second element of the list myList and save it in a variable myElement.
  • Line 3: We print it to the screen, print_int(myElement).

RELATED TAGS

ocaml
communitycreator

CONTRIBUTOR

Chinweuba Elijah Azubuike

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring