Haskell避免堆栈溢出而不牺牲性能

时间:2013-09-03 20:36:37

标签: haskell fold bytestring

以下代码遇到大量输入的堆栈溢出:

{-# 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]

是什么导致第一个代码段构建thunk,并且可以避免吗?是否可以编写第二个代码段,使其不依赖于(++)

2 个答案:

答案 0 :(得分:4)

L.length word + L.length (last words) <= 139

这就是问题所在。在每次迭代中,您将遍历累加器列表,然后

init words ++ [last words `L.append` " " `L.append` word]

追加到最后。显然这需要很长时间(与累加器列表的长度成比例)。一个更好的解决方案是懒惰地生成输出列表,交错处理与读取输入流(您不需要读取整个输入以输出第一个140个字符的推文)。

以下版本的程序在1秒钟内处理一个相对较大的文件(/usr/share/dict/words),同时使用O(1)空格:

{-# LANGUAGE OverloadedStrings, BangPatterns #-}

module Main where

import qualified Data.ByteString.Lazy.Char8 as L
import Data.Int (Int64)

genTweets :: L.ByteString -> L.ByteString
genTweets text | L.null text = ""
               | otherwise   = L.intercalate "\n\n" $ toTweets $ L.words text
  where

    -- Concatenate words into 139-character tweets.
    toTweets :: [L.ByteString] -> [L.ByteString]
    toTweets []     = []
    toTweets [w]    = [w]
    toTweets (w:ws) = go (L.length w, w) ws

    -- Main loop. Notice how the output tweet (cur_str) is generated as soon as
    -- possible, thus enabling L.writeFile to consume it before the whole
    -- input is processed.
    go :: (Int64, L.ByteString) -> [L.ByteString] -> [L.ByteString]
    go (_cur_len, !cur_str) []     = [cur_str]
    go (!cur_len, !cur_str) (w:ws)
      | lw + cur_len <= 139        = go (cur_len + lw + 1,
                                         cur_str `L.append` " " `L.append` w) ws
      | otherwise                  = cur_str : go (lw, w) ws
      where
        lw = L.length w

-- Notice the use of lazy I/O.
main :: IO ()
main = do dict <- L.readFile "/usr/share/dict/words"
          L.writeFile "tweets" (genTweets dict)

答案 1 :(得分:1)

p word words@(w:ws)

这种模式匹配导致对“尾部”的评估,这当然是foldr p [](w:ws)的结果,这是pw ws的结果,这导致ws与头部模式匹配等等。

请注意,foldr和foldl'将以不同方式拆分文本。 foldr将首先显示最短的推文,foldl'将使最短的推文显示在最后。


我会这样做:

genTweets' = unfoldr f where
  f [] = Nothing
  f (w:ws) = Just $ g w ws $ L.length w
  g w [] _ = (w, [])
  g w ws@(w':_) len | len+1+(L.length w') > 139 = (w,ws)
  g w (w':ws') len = g (w `L.append` " " `L.append` w') ws' $ len+1+(L.length w')