[Haskell-beginners] define action getInt like getLine

Rahul Kapoor rk at trie.org
Tue Feb 2 16:39:34 EST 2010

> Hi,
> how can I write an action
> getInt :: IO Int
> that works like
> getLine :: IO String

The most literal way to write getInt would be:

getInt :: IO Int
getInt = do
  s <- getLine
  return (read s)

which is just a more verbose version of:

getInt' =   read `fmap` getLine

The above versions don't do any error checking, so you might
prefer a getInt :: IO Maybe Int which returns Nothing in case the input
is not an integer.

You should read up on Monadic IO in Haskell. The Real World Haskell book
is probably a good starting point.


More information about the Beginners mailing list