Search code examples
haskellfoldequational-reasoning

Understanding different foldr statments


I understand simple foldr statements like

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

However, I'm having trouble with more complicated foldr statements, namely ones that take 2 parameters in the function, and with / and - computations. Could anyone explain the steps that occur to get these answers?

foldr (\x y -> (x+y)*2) 2 [1,3] = 22

foldr (/) 2 [8,12,24,4] = 8.0

Thanks.


Solution

  • The foldr function is defined as follows:

    foldr :: (a -> b -> b) -> b -> [a] -> b
    foldr _ a []     = a
    foldr f a (x:xs) = f x (foldr f a xs)
    

    Now consider the following expression:

    foldr (\x y -> (x + y) * 2) 2 [1,3]
    

    We'll give the lambda a name:

    f x y = (x + y) * 2
    

    Hence:

    foldr f 2 [1,3]
    -- is
    f 1 (foldr f 2 [3])
    -- is
    f 1 (f 3 (foldr f 2 []))
    -- is
    f 1 (f 3 2)
    -- is
    f 1 10
    -- is
    22
    

    Similarly:

    foldr (/) 2 [8,12,24,4]
    -- is
    8 / (foldr (/) 2 [12,24,4])
    -- is
    8 / (12 / (foldr (/) 2 [24,4]))
    -- is
    8 / (12 / (24 / (foldr (/) 2 [4])))
    -- is
    8 / (12 / (24 / (4 / (foldr (/) 2 []))))
    -- is
    8 / (12 / (24 / (4 / 2)))
    -- is
    8 / (12 / (24 / 2.0))
    -- is
    8 / (12 / 12.0)
    -- is
    8 / 1.0
    -- is
    8.0
    

    Hope that helped.