What is array.(n) in Ocaml?

Overview

Accessing array elements is an easy thing to do in Ocaml. The (n) method helps us with this. It helps return the element with the index position n in an array.

Syntax

array.(n)
Syntax for accessing array element with (n) method

Parameters

n: This represents the index position of the array element. If an index position is specified that is outside of the range of the array, an Invalid_argument exception is thrown.

Return value

An element of the array with index position n is returned.

Example

(*create some arrays*)
let evenNumbers = [| 2; 4; 6; 8; 10;|];;
let floatNumbers = [|3.423; 1.5;|];;
let letters = [|'a'; 'm'; 'e'; 'y'; 'z';|];;
let fruits = [|"banana"; "paw paw"; "apple";|];;
(*get and print some elements*)
print_int(evenNumbers.(2));;
print_string("\n");;
print_float(floatNumbers.(0));;
print_string("\n");;
print_char(letters.(4));;
print_string("\n");;
print_string(fruits.(1));;

Explanation

  • Lines 2–5: We created some arrays.
  • Lines 8–14: We access some elements in the created arrays using the (n) method and printed the elements to the console.

Free Resources