Reputation: 2950
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.
Upvotes: 4
Views: 392
Reputation: 47934
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.
Upvotes: 4
Reputation: 2540
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]
Upvotes: 4