Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find index of an Array element in OCaml

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

like image 638
sudheesh ks Avatar asked Feb 09 '23 10:02

sudheesh ks


1 Answers

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
like image 108
V. Michel Avatar answered Feb 11 '23 12:02

V. Michel