What is Array.get method in Ocaml?

Overview

With the get method of an array, we can get an element just by specifying its length. This method allows us to find any element present in an array.

Syntax

Array.get arr n
Syntax for Array.get method in Ocaml

Parameters

arr: The array whose element we want to get.

n: The index position of the element or value we want to find or access.

Return value

The value returned is an element of the array. If the number n specified is out of the range of the length of the array then an Invalid_argument exception is thrown.

Example

(*create some arrays*)
let evenNumbers = [| 2; 4; 6; 8; 10;|];;
let letters = [|'a'; 'm'; 'e'; 'y'|];;
let fruits = [|"banana"; "paw paw"; "apple";|];;
(*get their lengths*)
print_int(Array.get evenNumbers 3);;
print_string("\n");;
print_char(Array.get letters 0);; (* first element*)
print_string("\n");;
print_string(Array.get fruits 1);;
print_string("\n");;

Explanation

  • Lines 2–4: We create some arrays.
  • Lines 7–12: We get some array values using the Array.get method and print the results to the console.

New on Educative
Learn to Code
Learn any Language as a beginner
Develop a human edge in an AI powered world and learn to code with AI from our beginner friendly catalog
🏆 Leaderboard
Daily Coding Challenge
Solve a new coding challenge every day and climb the leaderboard

Free Resources