Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Convert data read from a file to a variable in Haskell

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading