[Haskell-cafe] Rewriting filter with foldr
PR Stanley
prstanley at ntlworld.com
Sun Sep 30 11:57:26 EDT 2007
>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) []
That's one neat solution but it also raises a few questions for me:
foldr :: (a -> b -> b) -> b -> [a] -> b
yet you've managed to squeeze in a function that takes only one
argument. How is this possible without GHCI blowing its top?
2. Could you please explain the role of the identity function (id) in
your code? Where's its argument, or is it sort of implicitly noted?
For example, is it the case that the second argument is held in
reserve and passed to the first function which would take it, hence
(x:) and id?
Many thanks, Paul
More information about the Haskell-Cafe
mailing list