[Haskell-beginners] Getting Stuff out of IO Handles

Arlen Cuss celtic at sairyx.org
Fri Jun 24 00:58:04 CEST 2011


On 24/06/2011 1:23 AM, Raphael Päbst wrote:
> Hey everyone!
> This is probably a stupid question,

No such thing. :)

> but is there a way to get stuff out of a IO handle?

You have to bind it in the IO monad. This means, for example, if you
have a handle called `h', in a do block:

  line <- hGetLine h

This is syntactic sugar for hGetLine h >>= (\line -> ...), where the
`...' is whatever follows in the do block.

> If I do something with an IO handle, reading in data from a file for
> example and then do something with the data, is there a way to get the
> results out of the handle, comparable to the return in a do block?

return is actually the opposite(!) -- it puts something *in* the monad.
I think you may have handles and the IO monad itself confused, but if
you'd like to post some sample code, we could show you how to achieve
what you want, and explain it more fully. :)

Here are some small examples of using handles and IO:

-- these are provided by System.IO:
stdin :: Handle
stdout :: Handle
hGetLine :: Handle -> IO String
hPutStrLn :: Handle -> String -> IO ()

-- from Control.Monad:
forever :: Monad m => m a -> m b

-- an example of using a handle:
copyLine :: Handle -> Handle -> IO ()
copyLine inh outh = do
  line <- hGetLine inh
  hPutStrLn outh line

-- The above 'do' block can be simplified to:
--   hGetLine inh >>= (\line -> hPutStrLn outh line)
-- and then to:
--   hGetLine inh >>= hPutStrLn outh

main :: IO ()
main = forever $ copyLine stdin stdout

.. it's a bit verbose, but perhaps helpful. If it's returning the result
of an op on a handle, it's much the same:

copyLineAndReturn :: Handle -> Handle -> IO String
copyLineAndReturn inh outh = do
  line <- hGetLine inh
  hPutStrLn outh line
  return line

-- hGetLine inh >>= (\line -> hPutStrLn outh line >> return line)

> Thanks
> 
> Raf

Cheers,

Arlen



More information about the Beginners mailing list