arraysocaml

How to find the index of the first non-zero element in an array


I am trying to find the index of the first non-zero number in an array.

Consider an array: [0;0;1;2;0;4;5;6]

The expected result will be index of number 1 which should return the index result of 2.

It will be great if the answer avoids the use of sequence operator and loops.


Solution

  • Without let, sequence op ;, for and while within the vanilla OCaml, I can write:

    class c = object (self)
      method f i = function
        | x::_ when x <> 0 -> i
        | _::xs -> self#f (i+1) xs
        | [] -> failwith "Got the answer from StackOverflow"
    end
    ;;
    
    (new c)#f 0 [0;0;1;2;0;4;5;6];;