将从文件读取的数据转换为 Haskell 中的变量

Convert data read from a file to a variable in Haskell

我有一个问题 - 我正在 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 returns IO String 是否有可能将其转换为 s String 以便我可以在纯 func 中使用它?

readFunc 具有类型 IO String,您可以在另一个 IO 表达式中使用它:

someIO = do
    textFromAFile <- readFunc
    -- use textFromFile (String) …
    -- …

例如:

someIO = do
    textFromAFile <- readFunc
    writeFunc (textFromAFile ++ "/")

它在 GHCi 终端中工作的原因是终端评估 IO a 个对象,因此虽然 textFromAFile 是一个 IO String,因此终端将 评估 textFromAFile.