3

Rather simple problem, but one that I am having trouble to overcome. None of the examples I find online works, not sure if its because they are outdated and something in IO were changed in last 2-3 years, or I a missing something obvious.

I know that reading file with readFile returns IO String and there is no easy way to get rid of it, but supposedly easy way to read file into normal String is s<- readFile "filename" which works in command line, but I just cant make it work in a function.

getString ::IO String
getString = readFile "Input.txt"

Is rather simple, but returns IO String instead of String, and I am having trouble making s<- readFile "filename" work. All I really want is simple function that returns file in a String and then I can deal with data in that string.

Ps I would love to see simple way to read file line by line function as well, as all examples seems to be incredibly complicated for what they are supposed to do and how easy is to perform those actions in any imperative programming language.

Aistis Taraskevicius
  • 781
  • 2
  • 10
  • 31

1 Answers1

9

There isn't a function that turns an IO String into a String. You can use do notation like so*:

main = do
  s <- readFile "somefile.txt"
  doSomethingWith s

doSomethingWith :: String -> IO ()
doSomethingWith str = putStrLn str

but you will only have access to s as a String inside the do block, or in functions that are applied to s, like doSomethingWith.


* You can also use the equivalent desugared version, main = readFile "someFile.txt" >>= \s -> doSomethingWith s.

Rein Henrichs
  • 15,437
  • 1
  • 45
  • 55