Rewriting filter with foldr

Hi filter :: (a -> Bool) -> [a] -> [a] filter f = foldr (\x -> \xs -> if (f x) then (x:xs) else xs) [] Somehow I feel this could be done more elegantly. What does the list think? Thanks, Paul

Perhaps a list comprehension better shows the intention of the filter function: filter p xs = [x | x <- xs, p x] You can literally read that as "take all x from xs that satisfy p".

On 9/30/07, PR Stanley
Hi filter :: (a -> Bool) -> [a] -> [a] filter f = foldr (\x -> \xs -> if (f x) then (x:xs) else xs) [] Somehow I feel this could be done more elegantly. What does the list think? Thanks, Paul
Well, note that foldr takes a function of x, which produces a function of xs. This function of xs either conses x onto it, or leaves it unchanged. We can write this down explicitly by removing the xs parameter and just writing what function should be produced: filter f = foldr (\x -> if (f x) then (x:) else id) [] -Brent
participants (3)
-
Brent Yorgey
-
PR Stanley
-
Roel van Dijk