문제

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.

도움이 되었습니까?

해결책

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.

다른 팁

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]
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top