[Haskell-beginners] define action getInt like getLine

Daniel Fischer daniel.is.fischer at web.de
Tue Feb 2 16:39:07 EST 2010

Am Dienstag 02 Februar 2010 22:20:03 schrieb kane96 at gmx.de:
> Hi,
> how can I write an action
> getInt :: IO Int
> that works like
> getLine :: IO String
> but for Int instead of String. I know that I can read the input with
> getLine and then convert it by using read, but don't know how to write
> it as an action. I tried getInt :: IO Int
> getInt read <- getLine
> but that doesn't work.

There are many possibilities.

The shortest is

getInt :: IO Int
getInt = readLn

another short and sweet is

getInt :: IO Int
getInt = fmap read getLine  -- or liftM read getLine

But neither of these deals well with malformed input, if that's a 
possibility to reckon with, use e.g. the reads function

getInt :: IO Int
getInt = do
    inp <- getLine
    case reads inp of
      ((a,tl):_) | all isSpace tl -> return a
      _ -> handle malformed input

More information about the Beginners mailing list