[Haskell-cafe] A Question about the IO type detection

Frerich Raabe raabe at froglogic.com
Fri Feb 13 12:09:02 UTC 2015

On 2015-02-13 13:00, Zongzhe Yuan wrote:
> i meet a problem when i was using readLn to read a int from user
> my function is like that
> do (some thing else that is working)
>      n <- readLn
>      (some thing else)
>      f n x1 x2 x3 ……
> f has the type of Int -> something else
> because the type in this function is fixed, if the type of n is not Int, it 
> will have exception
> However i want to detect whether the user input is valid or not


> How could i solve this problem?

readLn is a bit harsh when it comes to error reporting. You could use
getLine to read a string and then use readMaybe (in Text.Read) to see whether
it's a valid integer. Like:

   main = do
       s <- getLine
       case readMaybe s :: Maybe Int of
           Just i  -> f i
           Nothing -> putStrLn "Ouch!"

Frerich Raabe - raabe at froglogic.com
www.froglogic.com - Multi-Platform GUI Testing

More information about the Haskell-Cafe mailing list