What is the List.tl method in Ocaml?

Overview

In this shot, we'll learn how to get the tail of the list (the last items in a list), without iterating through the list, using the List.tl method in Ocaml.

Syntax

List.tl[listitems]
Syntax of the List.hd method

Parameter

The List.tl method receives the list for which we want to retrieve the last items.

Return value

The List.tl returns the list without the first item in the list.

Code example

Let's take a look at the following example:

open Printf
let x = List.tl[3; 2; 5;7];;
let () = List.iter (printf "%d ") x

Code explanation

  • Line 1: We call the Printf to print the list items later in the code.
  • Line 2: We create a list x with list items [3;2;5;7].
  • Line 3: We use the List.tl to get the items of the list without the first item which is 2, 5, 7. We then print it to the screen using the printf.

Free Resources