我有一種情況,我試圖連接兩個文本檔案 A 和 B 的內容。復雜之處在于 A 的內容中指定了 B 的位置。我創建了一個函式(下面的最小示例),它讀取 A,打開 B,然后嘗試將它們粘在一起,但坦率地說,這種方法似乎太容易不正確,我覺得它可能不是最好的方法。它可以編譯,但我無法測驗它,因為它找不到第二個檔案(可能與路徑有關,但我還沒有弄清楚是什么)。任何建議表示贊賞。
getIOFromIO :: IO String -> IO String
getIOFromIO orig = do
origContents <- orig
moreIO <- readFile origContents
return (origContents " " moreIO)
uj5u.com熱心網友回復:
該函式getIOFromIO應該可以正常作業,只要您向它傳遞一個讀取第一個檔案的 IO 操作,例如:
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://www.uj5u.com/qita/428839.html
