实现惰性的程序的最小修改可能是切换到惰性ST monad ( http://hackage.haskell.org/packages/archive/base/latest/doc/html/Control-Monad-ST-Lazy.html ),这段代码可以工作的地方:
import Control.Monad.ST.Lazy
import Data.Array.ST
import Data.Array.Unboxed
import Control.Monad
import Data.List
import Data.Maybe
prime :: Int -> [Int]
prime n = catMaybes $ runST $ do
arr <- strictToLazyST $ newArray ( 2 , n ) True :: ST s ( STUArray s Int Bool )
forM ( takeWhile ( \x -> x <= n ) [ 2 .. n ] ) $ \i -> do
if i == 83 then error "Reached 83" else return ()
ai <- strictToLazyST $ readArray arr i
if ai
then do
strictToLazyST $ forM_ [ i^2 , i^2 + i .. n ] $
\j -> writeArray arr j False
return (Just i)
else return Nothing
错误调用只是为了展示结果的真正惰性:
*Main> prime 10000
[2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79*** Exception: Reached 83
如果要避免 的中间列表Maybes
,例如,可以使用以下代码:
import Control.Monad.ST.Lazy
import Data.Array.ST
import Data.Array.Unboxed
import Control.Monad
import Data.List
import Data.Functor
prime :: Int -> [Int]
prime n = runST $ do
arr <- strictToLazyST $ newArray ( 2 , n ) True :: ST s ( STUArray s Int Bool )
let primesFrom i | i > n = return []
| otherwise = do
ai <- strictToLazyST $ readArray arr i
if ai then do
strictToLazyST $ forM_ [ i^2 , i^2 + i .. n ] $
\j -> writeArray arr j False
(i:) <$> primesFrom (i + 1)
else primesFrom (i + 1)
primesFrom 2