我如何在“不太严格”下面的表达式中使左手总和,以使我不评估整个列表xs。在此示例中,仅前3个元素足以知道第二个表达式(True)的结果。

xs=[1..10]
sum xs > 3


ghci:

λ> let xs = [1..10]
λ> :sp xs
xs = _
λ> sum xs > 3
True
λ> :sp xs
xs = [1,2,3,4,5,6,7,8,9,10]

最佳答案

使用lazy natural

Prelude Data.Number.Natural> let xs = [1..10] :: [Natural]
Prelude Data.Number.Natural> :sp xs
xs = _
Prelude Data.Number.Natural> sum xs > 3
True
Prelude Data.Number.Natural> :sp xs
xs = [Data.Number.Natural.S Data.Number.Natural.Z,
      Data.Number.Natural.S
        (Data.Number.Natural.S Data.Number.Natural.Z),
      Data.Number.Natural.S _,_,_,_,_,_,_,_]


要变得更懒惰,请使用foldr而不是foldl的方式,而使用sum的方式:

Prelude Data.Number.Natural> let xs = [1..10] :: [Natural]
Prelude Data.Number.Natural> let lazySum = foldr (+) 0
Prelude Data.Number.Natural> lazySum xs > 3
True
Prelude Data.Number.Natural> :sp xs
xs = Data.Number.Natural.S Data.Number.Natural.Z :
     Data.Number.Natural.S
       (Data.Number.Natural.S Data.Number.Natural.Z) :
     Data.Number.Natural.S _ : _

10-06 14:04