Search code examples
haskellfold

How does the foldr function in haskell work in this case?


So I'm new to haskell and I kind of encountered this following expression which i don't quiet get how it works: foldr (.) (+3) [(*2), (+5)] 13 it gives out the result: 42 now i know that foldr normally works in an example like: foldr (+) 0 [1,2,3] like: (1+(2+(0+3))) but with adding another function (.) I kind of got confused. So please if any of you could explain to me exactly how haskell interprets this expression that would be great, thanks!


Solution

  • Comments might have already solved this for you. However, if not:

    (.) is function composition:

    f . g
    = \x -> f $ g $ x
    = \x -> f (g x).
    

    Forms like (* 2) are sugar for functions of the form \x -> x * 2

    Now, observe that

    foldr op base [a,b]
    

    is the same as

    a `op` (b `op` base)
    

    of course, this works for higher numbers of arguments as well. For instance,

    foldr (+) 0 [1,2,3,4,5]
    

    is just

    1 + 2 + 3 + 4 + 5 + 0
    

    In your case, you ask about

    foldr (.) (+3) [(*2), (+5)]
    

    which is (for Integer)

    (*2) . (+5) . (+3)
    = \x -> (*2) $ (+5) $ (+3) $ x
    = \x -> (*2) $ (+5) $ x + 3
    = \x -> (*2) $ x + 3 + 5
    = \x -> (x + 3 + 5) * 2
    = \x -> x*2 + 16
    

    and so

    foldr (.) (+3) [(*2), (+5)] 13
    = (\x -> x*2 + 16) 13
    = 13*2 + 16
    = 26 + 16
    = 42