我有一個問題 - 我正在用 Haskell 寫一個檔案(我想在檔案中寫一個句子,每次我寫的時候我想覆寫檔案的內容,所以這個 func 對我來說完全沒問題)
writeFunc message = writeFile file message where
file = "abc.txt"
然后從同一個檔案中讀取
readFunc = do
let file = "abc.txt"
contents <- readFile file
return contents
然后我想把我讀過的東西保存在一個變數中:
在終端中這樣做
let textFromAFile = readFunc
結果如下:
*Main> let textFromAFile = readFunc
*Main> textFromAFile
"okay"
但是當我let textFromAFile = readFunc在我的代碼中使用時,代碼不會編譯
[1 of 1] Compiling Main ( tree.hs, interpreted )
tree.hs:109:29: error:
parse error (possibly incorrect indentation or mismatched brackets)
Failed, modules loaded: none.
我想將它保存在一個變數中,以便稍后在其他函式中使用它。為什么它在終端中作業但無法編譯,我該怎么做才能使它作業?ReadFunc 回傳 IO 字串,是否有可能將其轉換為 s 字串以便我可以在純函式中使用它?
uj5u.com熱心網友回復:
readFunc有 type IO String,你可以在另一個IO運算式中使用它:
someIO = do
textFromAFile <- readFunc
-- use textFromFile (String) …
-- …
例如:
someIO = do
textFromAFile <- readFunc
writeFunc (textFromAFile "/")
它在 GHCi 終端中作業的原因是終端評估IO a物件,因此 whiletextFromAFile是,因此IO String終端將評估 textFromAFile。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/394582.html
標籤:哈斯克尔
