How does foldr work?

后端 未结 10 2052
别跟我提以往
别跟我提以往 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:28

    An easy way to understand foldr is this: It replaces every list constructor with an application of the function provided. Your first example would translate to:

    10 - (11 - 54)

    from:

    10 : (11 : [])

    A good piece of advice that I got from the Haskell Wikibook might be of some use here:

    As a rule you should use foldr on lists that might be infinite or where the fold is building up a data structure, and foldl' if the list is known to be finite and comes down to a single value. foldl (without the tick) should rarely be used at all.

提交回复
热议问题