[Haskell-beginners] define action getInt like getLine

Stephen Blackheath [to Haskell-Beginners] mutilating.cauliflowers.stephen at blacksapphire.com
Sun Feb 7 15:25:13 EST 2010

Hi there,

Data types are required to start with a capital letter, so you'll have 
to call it MyDatatype.  I can't see where readLn is defined.  Can you 
paste a bit more of the code?  I don't quite understand how your reading 
of your own data type is meant to work - normally you would use read or 
reads from the Read type class.

A more subtle point - because of the way lazy evaluation works, it is 
generally better to use 'fail' rather than 'error' when in a monad.  In 
some monads it's possible that 'error' may do nothing.


kane96 at gmx.de wrote:
> 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

More information about the Beginners mailing list