Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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]

Any help would be appreciated.

like image 765
emi Avatar asked Feb 15 '23 19:02

emi


1 Answers

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.

like image 64
nlucaroni Avatar answered Feb 20 '23 17:02

nlucaroni