How to find index of an Array element in OCaml

5.6k Views Asked by At

I am trying to find the index of an integer array element in ocaml. How to do this recursively. Example code:let a = [|2; 3; 10|];; suppose I want to return the index of 3 in the array a. Any help appreciated. I am new to OCaml programming

3

There are 3 best solutions below

1
On BEST ANSWER

You check each of the elements recursively using an index

let rec find a x n =
if a.(n) = x then n 
else find a x (n+1);;

find a x 0;;

that will raise an exception (when n is bigger than the length of the array) in case the element is not part of the array.

0
On
type opt = Some of int | None;;

let find a i =
  let rec find a i n =
    if a.(n)=i then Some n
    else find a i (n+1)
  in
  try 
    find a i 0
   with _ -> None
;;

Test

# find a 3;;
- : int option = Some 1
# find [||] 3;;
- : int option = None
# find a 12;;
- : int option = None
0
On
let f xs x =
  let i = ref (-1) in
  let () = Array.iteri (fun n elt -> if x = elt then i := n else ()) xs in
  !i

The return value will be -1 if the element is not in the list.