How is foldl lazy?

前端 未结 4 2460
星月不相逢
星月不相逢 2021-02-19 16:33

There are lots of good questions and answers about foldl, foldr, and foldl\' in Haskell.

So now I know that:
1) foldl<

4条回答
  •  你的背包
    2021-02-19 17:28

    You know, that by definition:

    foldl op start (x1:x2:...:xN:[]) = ((start `op` x1) `op` x2) ...
    

    the line in foldl that does this is:

    foldl op a (x:xs) = foldl op (a `op` x) xs
    

    You are right that this is tail recursive, but observe that the expression

    (a `op` x)
    

    is lazy and at the end of the list, a huge expression will have been build that is then reduced. The difference to foldl' is just that the expression above is forced to evaluate in every recursion, so at the end you have a value in weak head normal form.

提交回复
热议问题