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
Asked
Active
Viewed 5,280 times
4

objmagic
- 1,028
- 1
- 9
- 18

sudheesh ks
- 351
- 1
- 8
- 15
3 Answers
4
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

V. Michel
- 1,599
- 12
- 14
3
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.

Pierre G.
- 4,346
- 1
- 12
- 25
-
I better understand this answer. May be other answers are better but I still have to learn more to understand them. And I think exception raising could be avoided by checking if n > (Array.length a -1) then 'some integer value to indicate not found' as first expression in function find. – sudheesh ks Nov 29 '15 at 06:38
1
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.

lambdapower
- 1,022
- 6
- 12