简体   繁体   中英

foldr and foldl function applied on div function in Haskell

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.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM