Ocaml循环尾递归

Ocaml loop tail recursion

我的作业基本完成了,只需要一定数量的工作测试样例。我唯一的问题是我无法弄清楚为什么这不起作用,我想知道我的理智。

let list_helper (x: 'a -> bool) head = if (x head) then true else false
let take_while (x: 'a -> bool) lst = 
    let rec take_while_helper x lst acc = match lst with
    | [] -> []
    | h::t -> if list_helper x h then take_while_helper x t (h::acc) else acc in take_while_helper x lst []

最后两个测试用例有效,但第一个无效。我做了另一个类似的功能,但它再次不起作用。看来我的函数不能很好地处理整数,我也不知道为什么。我想知道为什么它的行为不正确,因为我从逻辑上想通过它并且看起来它应该工作。也许我遗漏了一些关于整数和列表的东西。

在空列表的情况下,您还必须 return 累加器。而且您必须反转结果,因为您以错误的顺序将元素添加到累加器。

所以你的函数看起来像

let take_while (x: 'a -> bool) lst = 
  let rec take_while_helper lst acc = match lst with
  | [] -> acc
  | h::t -> if x h then (take_while_helper t (h::acc)) else acc
  in List.rev (take_while_helper lst [])