简体   繁体   中英

foldr result - Haskell

Could you explain me step by step the result of the second instruction?

I know how foldr works in this cases:

foldr (*) 1 [-3..-1]
-6

But I don't know how to deal with the function (\\yz -> y*3 + z) in a foldr expression.

foldr (\y z -> y*3 + z) 0 [1..4]
30

Let's look at the definition of foldr:

foldr f z []     = z 
foldr f z (x:xs) = f x (foldr f z xs) 

Now, in your example,

f y z = y*3 + z

So, just using the definitions:

foldr f 0 [1..4] = 
f 1 (foldr f 0 [2..4]) =
f 1 (f 2 (foldr f 0 [3,4])) =
f 1 (f 2 (f 3 (foldr f 0 [4]))) =
f 1 (f 2 (f 3 (f 4 (foldr f 0 [])))) =
f 1 (f 2 (f 3 (f 4 0))) =
f 1 (f 2 (f 3 12))) = 
f 1 (f 2 21) =
f 1 27 =
30

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