【问题标题】:Application of Tail-Recursion in OCaml尾递归在OCaml中的应用
【发布时间】:2013-11-15 06:45:51
【问题描述】:

我在 Ocaml 中编写了这个函数,但我想编写相同的东西,首先应用尾递归,然后 fold_left

let rec check fore list = 
    match list with 
    | [] -> [] | h :: t -> 
        if fore h 
        then h :: check fore t 
        else check fore t ;;

这是我到目前为止所做的。它返回一个大于给定参数的列表(即最初给定列表时)。示例:check (fun a -> a >= 6 )[5;4;8;9;3;9;0;2;3;4;5;6;61;2;3;4] 返回# - : int list = [8; 9; 9; 6; 61]

任何帮助将不胜感激。

【问题讨论】:

    标签: recursion functional-programming ocaml tail-recursion


    【解决方案1】:

    你为什么不用List.filter

    List.filter (fun a -> a >= 6) [5;4;8;9;3;9;0;2;3;4;5;6;61;2;3;4]
    

    【讨论】:

    • 事实上,filter 是尾递归的。
    【解决方案2】:

    对于尾递归,您必须向check 函数添加一个附加参数(累加器)。这通常通过使用累加器的初始值调用的附加内部函数是透明的。

    let rec check acc fore list = 
      match list with 
      | [] -> acc
      | h :: t -> 
        if fore h 
          then check (h::acc) fore t 
          else check acc fore t
    

    您可能需要在最后(第三行)输入List.rev,但在这种情况下可能没有必要。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-07
      • 1970-01-01
      • 1970-01-01
      • 2013-05-20
      • 2016-03-21
      相关资源
      最近更新 更多