Learning Haskell and FP
Lars Lundgren
d95lars@dtek.chalmers.se
Thu, 4 Jan 2001 09:45:19 +0100 (MET)
On Wed, 3 Jan 2001, Michael Zawrotny wrote:
> 1. How the #$!? do I read some data from a file. Good, I've
> got the data, now I can work on it. Nope, now I have an "IO
> thingie" whatever that is, but all of the standard functions want
> a regular "thingie" now what?
>
I do not know if you actually wanted an answer to this, but I'm sick of
hearing this FAQ everywhere when the answer is so simple. There are
exactly two ways to do this (one of them is actually syntactic sugar for
the other).
1. Use the do notation:
do regularThingie <- IOThingie
return (doWhateverYouWantWith regularThingie)
2. Use bind ( >>= ):
IOThingie >>=
\regularThingie -> return (doWhateverYouWantWith regularThingie)
Note: Both constructs produces IO thingies. This is the real beauty of it,
if you have a value that is dependent on the environment (i.e. a IO value)
you can use it as a regular value inside one of the above constructs, but
the result will always be an IO value (The result will depend on the
environment because it uses a value dependent of the environment). This is
no problem, just accept it.
Can everyone include an answer to this FAQ everywhere, phleaze!
/Lars L