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.
array.(n)
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.
An element of the array with index position n
is returned.
(*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));;
(n)
method and printed the elements to the console.