Home > Mobile >  Convert data read from a file to a variable in Haskell
Convert data read from a file to a variable in Haskell

Time:12-27

I have a problem - I am writing in a file in Haskell (I wanna write a sentence in the file and everytime I write in it I want to overwrite the content of the file so this func does the work for me completely fine)

writeFunc message = writeFile file message where
    file = "abc.txt"

And then reading from the same file

readFunc = do
    let file = "abc.txt"
    contents <- readFile file
    return contents

And then I wanna save the things I have read in a variable:

In the terminal doing this

let textFromAFile = readFunc

results into this:

*Main> let textFromAFile = readFunc
*Main> textFromAFile
"okay" 

But when I use let textFromAFile = readFunc inside my code, the code wont compile

[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. 

I wanna save it in a variable so I can use it later in other functions. Why it works in the terminal but wont compile and what I can do to make it work? ReadFunc returns IO String and is there a possible way to convert it to s String so I can use it in a pure func?

CodePudding user response:

readFunc has type IO String, you can use it in another IO expression with:

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

for example:

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

The reason it works in the GHCi terminal is that the terminal evaluates IO a objects, so while textFromAFile is an IO String, and the terminal will thus evaluate textFromAFile.

  • Related