【发布时间】:2015-09-21 19:57:47
【问题描述】:
如何在恒定空间中使用一元动作折叠惰性列表?我要解决的问题是聚合一个大文件,我相信为了性能,我需要可变性。我有一个使用可变向量在 ST 中工作的实现,但它使用了太多内存。下面是我正在尝试的一个例子。我还对 Conduit 进行了短暂的试验,但似乎没有任何改进。
ST forM_:
import Control.Monad (forM_)
import Control.Monad.ST.Trans as STT
import Control.Monad.Identity as Identity
testST :: Int
testST = do
Identity.runIdentity $ STT.runST $ do
a <- STT.newSTRef 0
forM_ [1..10000000] (\x -> do
a' <- STT.readSTRef a
STT.writeSTRef a (a' + x)
)
STT.readSTRef a
导管:
import Data.Conduit (($=),(=$),($$))
import qualified Data.Conduit as C
import qualified Data.Conduit.List as CL
testCL :: IO Int
testCL = CL.sourceList [1..10000000] $$ CL.foldM (\a x -> return (a + x)) 0
【问题讨论】:
-
对于性能调整:看起来
STT s Identity将比通常的ST s有一些分配开销;如果您不需要特殊的STT权力,您可能只想使用ST。 -
@dfeuer 实际上我可能会删除它,但我把它放在最初期望需要嵌入
Either的实现中,它被转移了。感谢您的提示!
标签: performance haskell