[Haskell-beginners] define action getInt like getLine

kane96 at gmx.de kane96 at gmx.de
Sun Feb 7 15:03:00 EST 2010


thanks so far.
I used "getInt = fmap read getLine", because I think it's enough for me

I have to do it for a more complex case of reading an own data type (myDatatype) with is deriving Show and return an error otherwise.
I tried the following which didn't work:

readMyDatatype :: IO myDatatype
readMyDatatype = do
  if readLn == (show readLn)
  then return readLn
  else do error "input error"


-------- Original-Nachricht --------
> Datum: Tue, 2 Feb 2010 22:39:07 +0100
> Von: Daniel Fischer <daniel.is.fischer at web.de>
> An: beginners at haskell.org
> CC: kane96 at gmx.de
> Betreff: Re: [Haskell-beginners] define action getInt like getLine

> 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

-- 
NEU: Mit GMX DSL über 1000,- ¿ sparen!
http://portal.gmx.net/de/go/dsl02


More information about the Beginners mailing list