Recursion 将递归限制为浮点列表的前三个元素

Recursion 将递归限制为浮点列表的前三个元素,recursion,functional-programming,ocaml,reason,Recursion,Functional Programming,Ocaml,Reason,我不熟悉函数式编程ReasonML/OCaml 我有一张花车的清单。我想得到列表的前三个非零项,不要更多。项目可以是正、负和零 在提取前三个非零浮点之前,如何限制递归 我想做一些类似的事情: switch (list) { | [first, second, third, ...rest] => (first +. second +. third) /. 3.0 | _ => 0.0 }; 但我怎样才能保证第一、第二和第三个是非零浮动呢?如果是,则递归地丢弃它们,直到找到三

我不熟悉函数式编程ReasonML/OCaml

我有一张花车的清单。我想得到列表的前三个非零项,不要更多。项目可以是正、负和零

在提取前三个非零浮点之前,如何限制递归

我想做一些类似的事情:

switch (list) {
  | [first, second, third, ...rest] => (first +. second +. third) /. 3.0
  | _ => 0.0
};
但我怎样才能保证第一、第二和第三个是非零浮动呢?如果是,则递归地丢弃它们,直到找到三个非零浮点-或返回0.0。

明白了

可以使用List.filer筛选出等于零的元素

let filtered = List.filter (fun item => item != 0.0) list;
switch (filtered) {
  | [first, second, third, ...rest] => (first +. second +. third) /. 3.0
  | _ => 0.0
};

使用递归实现这一点的一个更好的方法是使其更为通用:与其查找3个第一个非零,不如查找n个第一个非零

下面是一个OCaml实现,我不知道原因

let rec find_n l n ~f =
  if n = 0 then []
  else match l with
  | [] -> failwith "Cannot find enough items"
  | h::t ->
      if f h then
        h :: (find_n t (n-1) ~f)
      else
        find_n (t n ~f)
这是函数的签名:

val find_n : 'a list -> int -> f:('a -> bool) -> 'a list = <fun>

请注意,即使在找到三个非零浮点之后,这也将遍历整个列表。非常感谢!对于那些希望看到RationalML语法的人,可以使用此工具在OCaml和RationalML片段之间进行转换。
let find_n l n ~f =
  let rec loop l' n' acc =
    if n' = 0 then acc else
      match l' with
      | [] -> failwith "Cannot find enough items"
      | h::t ->
          if f h then
            loop t (n' - 1) (h::acc)
          else
            loop t n' acc
  in
  loop l n []