1
votes

I am really confused on how foldr and foldl works. Like for example using like this on the list [1,2,3]

foldr (+) 0 => 1 : (2 :(3:([])) 
             => 1 + (2 +(3+0)) = 6

And this makes sense because each : is replaced by the + sign and the empty set by 0.

But when I type the following two lines in the ghci I get:

foldr div 7 [13,6,19]   -- gives me 4 
foldl div 7 [13,6,19]   -- gives me 0

I thought I would get a list in which each element was divided by 7 but instead I just get one element. Can someone please walk me through how the ghci calculates this.

1
No, if you want to div every element, you need map (`div` 7) [13, 6, 19] - Willem Van Onsem
foldr div 7 [13, 6, 19] means you calculate div 13 (div 6 (div 19 7)) == div 13 (div 6 2) == div 13 3 == 4, for foldl it is the opposite: div (div (div 7 13) 6) 19 == div (div 0 6) 19 == div 0 19 == 0. - Willem Van Onsem
Also, div is integer division, so it rounds down (you can get the remainder with rem). Your foldl example rounds 7/13 down to 0 and then 0/6 and 0/19 are zero. Your foldr example rounds 19/7 to 2, then 6/2 is 3, and 13/3 rounds down to 4. - Davislor
Note that you didn't get a list where each element was summed with 0 in the first example. - David Young

1 Answers

6
votes

foldr looks like this:

foldr f z [x1, x2, ..., xn] == x1 `f` (x2 `f` ... (xn `f` z)...)

So in your case:

foldr div 7 [13, 6, 19] == 13 `div` (6 `div` (19 `div` 7))

You can look stuff like this up on Hoogle! If you want a list with all numbers divided by 7, use map.