Domanda

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.

È stato utile?

Soluzione

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.

Altri suggerimenti

Why don't you use List.filter ?

List.filter (fun a -> a >= 6) [5;4;8;9;3;9;0;2;3;4;5;6;61;2;3;4]
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top