sudheesh ks
sudheesh ks

Reputation: 371

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

Upvotes: 4

Views: 5953

Answers (3)

V. Michel
V. Michel

Reputation: 1619

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

Upvotes: 4

lambdapower
lambdapower

Reputation: 1032

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.

Upvotes: 1

Pierre G.
Pierre G.

Reputation: 4431

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.

Upvotes: 3

Related Questions