我遇到了一种情况,我试图连接两个文本文件的内容,A和B。复杂的是,B的位置是在A的内容中指定的,我创建了一个函数(下面的最小示例),它读取A,打开B,然后尝试将它们连接在一起,但是坦白地说,这个方法似乎太简单了,不太正确,我觉得这可能不是最好的方法。它编译,但我无法测试它,因为它找不到第二个文件(大概是与路径有关,但我还没有弄清楚是什么)。任何建议都很感激。
getIOFromIO :: IO String -> IO String
getIOFromIO orig = do
origContents <- orig
moreIO <- readFile origContents
return (origContents ++ " " ++ moreIO)发布于 2022-02-19 18:30:48
如果您传递一个读取第一个文件的IO操作,getIOFromIO函数应该工作得很好,如下所示:
getIOFromIO (readFile "foo.tmp")并提供foo.tmp的整个内容,包括任何前面或后面的空白(如尾随换行符)是所需文件名的一部分。
下面的自给示例演示了它的使用:
setup :: String -> String -> IO ()
setup file1 file2 = do
writeFile file1 file2 -- put name of file2 in file1
writeFile file2 $ "body\n"
-- unmodified from your question
getIOFromIO :: IO String -> IO String
getIOFromIO orig = do
origContents <- orig
moreIO <- readFile origContents
return (origContents ++ " " ++ moreIO)
main = do
setup "foo.tmp" "bar.tmp"
txt <- getIOFromIO (readFile "foo.tmp")
print txt它应产生产出:
"bar.tmp body\n"
^^^^^^^ ^^^^
| ` contents of second file (bar.tmp)
|
`- contents of first file (foo.tmp)https://stackoverflow.com/questions/71183218
复制相似问题