简体   繁体   English

尾递归在OCaml中的应用

[英]Application of Tail-Recursion in OCaml

I wrote this function in Ocaml but I want to write the same thing first applying tail-recursion and then fold_left . 我在Ocaml中编写了这个函数,但我想先编写同样的东西,首先应用tail-recursion然后再使用fold_left

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

This is what I did so far. 这就是我到目前为止所做的。 It returns a list (that is when given a list initially) that is greater than a given parameter. 它返回一个大于给定参数的列表(最初给定列表时)。 Example: check (fun a -> a >= 6 )[5;4;8;9;3;9;0;2;3;4;5;6;61;2;3;4] returns # - : int list = [8; 9; 9; 6; 61] 示例: 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] # - : int list = [8; 9; 9; 6; 61]

Any help would be appreciated. 任何帮助,将不胜感激。

你为什么不使用List.filter

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

For tail-recursion, you have to add an additional parameter (an accumulator) to the check function. 对于尾递归,您必须向check函数添加一个附加参数(累加器)。 Often this is transparent by an additional internal function that's called with the initial value of the accumulator. 通常,这是通过使用累加器的初始值调用的附加内部函数来透明的。

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

You may need to do a List.rev at the end (line three), but in this case it may not be necessary. 您可能需要在结尾处执行List.rev (第三行),但在这种情况下可能没有必要。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM