Is foldl ever preferable to its strict cousin, foldl'?

前端 未结 2 1066
别跟我提以往
别跟我提以往 2021-02-18 15:14

Haskell has two left fold functions for lists: foldl, and a \"strict\" version, foldl\'. The problem with the non-strict foldl is that it

2条回答
  •  清歌不尽
    2021-02-18 15:31

    foldl and foldl' are not semantically equivalent. Trivial counterexample:

    Prelude Data.List> foldl (\x y -> y) 0 [undefined, 1]
    1
    Prelude Data.List> foldl' (\x y -> y) 0 [undefined, 1]
    *** Exception: Prelude.undefined
    

    In practice, however, you usually want the strict foldl' for the reasons you mentioned.

提交回复
热议问题