[Haskell-cafe] Rewriting filter with foldr
byorgey at gmail.com
Sun Sep 30 09:51:09 EDT 2007
On 9/30/07, PR Stanley <prstanley at ntlworld.com> wrote:
> 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
> 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) 
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the Haskell-Cafe