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

前端 未结 2 1067
别跟我提以往
别跟我提以往 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:18

    When foldl and foldl' wouldn't produce the same result, as in hammar's example, the decision has to be made according to the desired outcome. Apart from that, you'd use foldl rather than foldl' if the folded function is a constructor (applying a constructor creates a value in WHNF, there's no point in forcing it to WHNF again), and in foldl (.) id functions where forcing WHNF doesn't gain anything either. Apart from these exceptional cases, foldl' is the method of choice.

提交回复
热议问题