Search code examples
functional-programmingocamlocaml-batteries

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


Solution

  • 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.