Reading “Real World Haskell”, on page 95 the author provides an example:
myFoldl f z xs = foldr step id xs z
where step x g a = g (f a x)
My question is: Why does this code compile? foldr takes only three arguments – but here, it is passed four: step, id, xs, z.
For example, this doesn’t work (because sum expects one):
sum filter odd [1,2,3]
instead I must write:
sum $ filter odd [1,2,3]
Here’s the type of
foldr:Can we figure out how it becomes a four-argument function? Let’s give it a try!
we’re giving it
id :: d -> das the second parameter (b), so let’s substitute that into the type:in Haskell,
a -> a -> ais the same asa -> (a -> a), which gives us (removing the last set of parentheses):let’s simplify, by substituting
efor(a -> (d -> d) -> (d -> d))andffor(d -> d), to make it easier to read:So we can plainly see that we’ve constructed a four-argument function! My head hurts.
Here’s a simpler example of creating an n + 1-argument function from an n-arg func:
idis a function of one argument.But I just gave it 5 args!