我怎样才能在“不太严格”下面的表达式中进行左手求和,这样我就不会评估整个列表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]
我怎样才能在“不太严格”下面的表达式中进行左手求和,这样我就不会评估整个列表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]
使用懒惰自然。
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 _ : _