Reputation: 927
I'm attempting to rewrite List.filter manually so far I have this:
let rec filter f = function
|[] -> []
|x::xs -> if f x = true then x @ filter f xs
else filter f xs;;
Upvotes: 1
Views: 617
Reputation: 10350
I'd add to the accepted answer that recognizing and applying functional patterns may be as important as mastery of recursion and pattern matching. And probably the first of such patterns is folding.
Implementing your task with folding takes a terse:
let filter p ls = List.foldBack (fun l acc -> if p l then l::acc else acc) ls []
Upvotes: 6
Reputation: 4280
Operator @
appends 2 lists so x
in if ... then ... else
expression is supposed to be of type list
.
You probably meant to use list cons operator ::
. Also you don't need to compare the result of function f
application to true
.
let rec filter f = function
|[] -> []
|x::xs -> if f x then x :: filter f xs
else filter f xs
[1;2;3;4;5;6;7;8;9] |> filter (fun x -> x % 2 = 0)
val it : int list = [2; 4; 6; 8]
Note: this function is not tail recursive so you'll get stack overflow exception with big lists.
Upvotes: 3