如何在列表中查找第一个非零元素的索引(语言 - Ocaml)

时间:2014-07-26 07:39:50

标签: arrays ocaml

我试图在数组中找到第一个非零数字的索引。在这里进一步解释是预期的,

考虑一个数组 - [0;0;1;2;0;4;5;6]

预期结果将是数字1的索引,返回结果索引应为 2nd

如果答案避免使用序列运算符和循环,那将会很棒。

提前致谢!

1 个答案:

答案 0 :(得分:3)

如果没有let,在香草OCaml中序列为op ;forwhile,我可以写道:

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];;
相关问题