簡體   English   中英

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 []
  • take_while (fun _ -> true) [1; 2; 3] take_while (fun _ -> true) [1; 2; 3]評估為[1; 2; 3] [1; 2; 3] [1; 2; 3] 這一項不起作用。
  • take_while ((=) "a") ["a"; "a"; "b"; "a"] take_while ((=) "a") ["a"; "a"; "b"; "a"]計算結果應為["a"; "a"] ["a"; "a"] 可以正常工作。
  • take_while (fun _ -> false) ["say"; "anything"] take_while (fun _ -> false) ["say"; "anything"]都應評估為[] 可以正常工作。

最后兩個測試用例有效,但第一個無效。 我做了另一個類似的功能,再次它不起作用。 看來我的函數不能很好地處理整數,而且我也不知道為什么。 我想知道為什么它的行為不正確,因為我雖然從邏輯上通過它,但似乎應該可以工作。 也許我缺少有關整數和列表的信息。

如果列表為空,還必須返回累加器。 而且,由於將元素以錯誤的順序添加到累加器中,因此必須反轉結果。

所以你的功能看起來像

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 [])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM