【发布时间】:2013-09-03 20:36:36
【问题描述】:
以下代码在大输入时遇到堆栈溢出:
{-# LANGUAGE DeriveDataTypeable, OverloadedStrings #-}
import qualified Data.ByteString.Lazy.Char8 as L
genTweets :: L.ByteString -> L.ByteString
genTweets text | L.null text = ""
| otherwise = L.intercalate "\n\n" $ genTweets' $ L.words text
where genTweets' txt = foldr p [] txt
where p word [] = [word]
p word words@(w:ws) | L.length word + L.length w <= 139 =
(word `L.append` " " `L.append` w):ws
| otherwise = word:words
我假设我的谓词正在构建一个 thunk 列表,但我不确定为什么或如何解决它。
使用foldl' 的等效代码运行良好,但需要很长时间,因为它不断地追加,并使用大量内存。
import Data.List (foldl')
genTweetsStrict :: L.ByteString -> L.ByteString
genTweetsStrict text | L.null text = ""
| otherwise = L.intercalate "\n\n" $ genTweetsStrict' $ L.words text
where genTweetsStrict' txt = foldl' p [] txt
where p [] word = [word]
p words word | L.length word + L.length (last words) <= 139 =
init words ++ [last words `L.append` " " `L.append` word]
| otherwise = words ++ [word]
是什么导致第一个 sn-p 建立 thunk,可以避免吗?是否可以编写第二个 sn-p 使其不依赖(++)?
【问题讨论】:
标签: haskell fold bytestring