I want to read a whole file into a string and then use the function lines to get the lines of the string. I’m trying to do it with these lines of code:
main = do
args <- getArgs
content <- readFile (args !! 0)
linesOfFiles <- lines content
But I’m getting the following error by compiling ad it fails:
Couldn't match expected type `IO t0' with actual type `[String]'
In the return type of a call of `lines'
In a stmt of a 'do' block: linesOfFiles <- lines content
I thought by binding the result of readFile to content it will be a String DataType, why isn’t it?
It is a
Stringindeed, that’s not what the compiler complains about. Let’s look at the code:Now
contentis, as desired, a plainString. And thenlines contentis a[String]. But you’re using the monadic binding in the next linein an
IO ()do-block. So the compiler expects an expression of typeIO somethingon the right hand side of the<-, but it finds a[String].Since the computation
lines contentdoesn’t involve anyIO, you should bind its result with aletbinding instead of the monadic binding,is the line you need there.