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.
divevery element, you needmap (`div` 7) [13, 6, 19]- Willem Van Onsemfoldr div 7 [13, 6, 19]means you calculatediv 13 (div 6 (div 19 7)) == div 13 (div 6 2) == div 13 3 == 4, forfoldlit is the opposite:div (div (div 7 13) 6) 19 == div (div 0 6) 19 == div 0 19 == 0. - Willem Van Onsemdivis integer division, so it rounds down (you can get the remainder withrem). Yourfoldlexample rounds 7/13 down to 0 and then 0/6 and 0/19 are zero. Yourfoldrexample rounds 19/7 to 2, then 6/2 is 3, and 13/3 rounds down to 4. - Davislor0in the first example. - David Young(/)instead ofdiv: stackoverflow.com/questions/48611896/foldr-and-foldr1-haskell - Andrey Tyukin