以下代码会遇到大输入的堆栈溢出:
{-# 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 列表,但我不确定为什么或如何修复它。
using 的等效代码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]
是什么导致第一个片段建立 thunk,可以避免吗?是否可以编写第二个片段使其不依赖(++)
?