[Haskell-cafe] Rewriting filter with foldr

Brent Yorgey byorgey at gmail.com
Sun Sep 30 09:51:09 EDT 2007


On 9/30/07, PR Stanley <prstanley at ntlworld.com> wrote:
>
> 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
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070930/b42b46d7/attachment.htm


More information about the Haskell-Cafe mailing list