How does foldr work?

后端 未结 10 2057
别跟我提以往
别跟我提以往 2020-12-04 06:37

Can anybody explain how does foldr work?

Take these examples:

Prelude> foldr (-) 54 [10, 11]
53
Prelude> foldr (\\x y -> (x+y)/2) 54 [12, 4,         


        
10条回答
  •  一个人的身影
    2020-12-04 07:42

    The easiest way to understand foldr is to rewrite the list you're folding over without the sugar.

    [1,2,3,4,5] => 1:(2:(3:(4:(5:[]))))
    

    now what foldr f x does is that it replaces each : with f in infix form and [] with x and evaluates the result.

    For example:

    sum [1,2,3] = foldr (+) 0 [1,2,3]
    
    [1,2,3] === 1:(2:(3:[]))
    

    so

    sum [1,2,3] === 1+(2+(3+0)) = 6
    

提交回复
热议问题