Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 623
p0ny Avatar asked Nov 24 '25 15:11

p0ny


1 Answers

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.

like image 67
Aadit M Shah Avatar answered Nov 27 '25 05:11

Aadit M Shah



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!