Problems with IO actions

Previous Topic Next Topic
 
classic Classic list List threaded Threaded
2 messages Options
Reply | Threaded
Open this post in threaded view
|

Problems with IO actions

Adam Bergmark
I have an issue with IO actions.
At the moment I have the following snippet of code, which works as I  
expect it to.

mapM_ (writeChan ch) . lines =<< hGetContents h

That is, it gets each line in the file and writes it to the channel.
Previously I had just:

writeChan ch =<< hGetContents h

but when i readChan this I get the empty string every time.

I have two questions:
  * I'm still a little unsure of why mapM_, sequence and the like are  
necessary, could someone please explain this, or point me somewhere  
where I can read up on it?
  * Why does this problem occur when there is only one action to  
perform?


Cheers
/ Adam Bergmark
Reply | Threaded
Open this post in threaded view
|

Problems with IO actions

Jason Dusek
2009/07/01 Adam Bergmark <[hidden email]>:
>?* I'm still a little unsure of why mapM_, sequence and the
>   like are necessary, could someone please explain this, or
>   point me somewhere where I can read up on it?

  Say we have a list of `IO` actions (type `[IO a]`). We can't
  run lists directly; the runtime runs `IO` action (type `IO
  something`). It's easy to do the translation but we'd rather
  not do it all the time: here's an easy recursive definition of
  `sequence`:

    sequence ops             =  recurse [] ops
     where
      recurse acc [       ]  =  return $ reverse acc
      recurse acc (op:rest)  =  do
        result              <-  op
        sequence' (result:acc) rest

  The other operations are further conveniences that can be
  built up from `sequence`.

> * Why does this problem occur when there is only one action to
>   perform?

  Do you close the handle?

--
Jason Dusek