I'm learning to use input and output in Haskell. I'm trying to generate a random number and output it to another file. The problem is that the random number seems to be returning an IO Int
, something that I can't convert to a String
using show
.
Could someone give me a pointer here?
It's helpful if you show us the code you've written that isn't working.
Anyway, you are in a do
block and have written something like this, yes?
main = do
...
writeFile "some-file.txt" (show generateRandomNumberSomehow)
...
You should instead do something like this:
main = do
...
randomNumber <- generateRandomNumberSomehow
writeFile "some-file.txt" (show randomNumber)
...
The <-
operator binds the result of the IO Int
value on the right to the Int
-valued variable on the left. (Yes, you can also use this to bind the result of an IO String
value to a String
-valued variable, etc.)
This syntax is only valid inside a do
block. It's important to note that the do
block will itself result in an IO value --- you can't launder away the IO-ness.