haskell写大字符串

标签 haskell

你好 Stackoverflow 社区。

我是 Haskell 的新手,我注意到将大字符串写入文件 writeFilehPutStr 非常慢。

对于 1.5 Mb 的字符串,我的程序(用 ghc 编译)大约需要 2 秒,而 C++ 中的“相同”代码只需要大约 0.1 秒。 该字符串是从包含大约 10000 个元素的列表中生成的,然后使用 writeFile 转储。我还尝试使用 mapM_hPutStr 遍历列表,结果相同。

有没有更快的写大字符串的方法?

更新

正如@applicative 所指出的,下面的代码很快就完成了一个 2MB 的文件

main = readFile "input.txt" >>= writeFile "ouput.txt"

所以我的问题似乎在别的地方。这是我的两个实现 编写列表(WordIndex 和 CoordList 是 Map 和 List 的类型别名)

使用 hPutStrLn

-- Print to File
indexToFile :: String -> WordIndex -> IO ()
indexToFile filename index =
    let 
        indexList = map (\(k, v) -> entryToString k v)  (Map.toList index)
    in do
        output <- openFile filename WriteMode
        mapM_ (\v -> hPutStrLn output v) indexList
        hClose output


-- Convert Listelement to String
entryToString :: String -> CoordList -> String
entryToString key value = (embedString 25 key) ++ (coordListToString value) ++ "\n"

用写文件

-- Print to File
indexToFile :: String -> WordIndex -> IO ()
indexToFile filename index = writeFile filename (indexToString "" index)

-- Index to String
indexToString :: String -> WordIndex -> String
indexToString lead index = Map.foldrWithKey (\k v r -> lead ++ (entryToString k v) ++ r) "" index

也许你们可以帮助我在这里找到一个加速点。

提前致谢

最佳答案

这是众所周知的问题。默认的 Haskell String 类型是简单的 [Char] 并且根据定义很慢,如果它是惰性构造的(通常情况)则非常慢。但是,作为列表,它允许使用列表组合器进行简单干净的处理,并且在性能不是问题时很有用。如果是,应该使用 ByteStringText 包。 ByteString 更好,因为它与 ghc 一起提供,但不提供 unicode 支持。 ByteString-based utf8 包在 hackage 上可用。

关于haskell写大字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11420508/

相关文章:

haskell - Monad Transformer 与将参数传递给函数

haskell - 为什么我不能在 Haskell 中捕获与 () 不同的 IO 中的异常?

Haskell 编写一个函数来执行列表上的输入功能

haskell - 在haskell中模拟C函数静态变量

haskell - 我试图破解 Haskell,并从 GHC 收到 "Inaccessiable code"错误。这是什么意思?

sqlite - Haskell-尝试查询刚刚创建的表时出现持久错误

haskell - (^) 的奇怪行为

haskell - fmap 替换解析树中的文字

haskell - 越界 `select` 即使我 `constrain` 索引

haskell - 在类型构造函数中部分应用类型