简体   繁体   中英

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 .

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] # - : 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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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