2013-09-29 52 views
4

我怎麼能在下面的表達式中使左手總和「不太嚴格」,這樣我就不會評估整個列表xs。在這個例子中,只有前3個元素足以知道第二個表達式的結果(True)。如何在haskell中定義一個lazier求和函數?

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] 

回答

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 _ : _ 
+0

我也嘗試定義與'foldr'總和,但它評估整數的整個列表。我想我應該使用自然,即使'foldr'。 – vis

相關問題