我怎样才能在下面的表达式中对左手总和“不严格”,这样我就不会评估整个列表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]
答案 0 :(得分:8)
使用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 _ : _