【发布时间】:2016-10-01 09:37:27
【问题描述】:
我需要在同一个函数中读取、修改然后更新一些文件。理想的解决方案(见下文)行不通,这是错误的。 “最差”的解决方案有效。
-- Ex. "Pseudocode" - Doesn't work.
ideal = let pathFile = "C:\\TEMP\\Foo.txt"
in readFile pathFile >>= writeFile pathFile . (++ "!")
-- It works.
worst = do
let pathFile = "C:\\TEMP\\Foo.txt"
h <- openFile pathFile ReadMode
cs <- hGetContents h
(temp_Foo,temp_handle) <- openTempFile pathFile
hPrint temp_handle $ cs ++ "!"
hClose temp_handle
removeFile pathFile
renameFile temp_Foo pathFile
我宁愿避免 Reid Burton 在 2010 年提出的“简单但丑陋的解决方法”:
doit file = do
contents <- readFile file
length contents `seq` (writeFile file $ process contents)
有没有更好的解决方案?
【问题讨论】:
-
好吧,您可以使用导管/管道解决方案。 :)
-
@Sibi 这些库非常庞大。我认为这需要很长时间才能掌握。另外,我不认为用大炮杀死蚊子。
-
@AlbertoCapitani 你不需要大炮来杀死蚊子——但你也不需要超级计算机(按照 70 年代的标准)来打电话。
-
如果您使用
import qualified Data.Text.IO as T,则您有严格的文本,ideal工作正常T.readFile pathFile >>= T.writeFile pathFile . (<> "!")。text包是处理文本的标准方法。 -
@Michael 谢谢你,但我选择这个例子只是为了简单。我使用集合和地图以及其他更复杂的结构。