[Haskell-cafe] [Newbie question] -- Looping stdin until condition is met

Don Stewart dons at galois.com
Fri May 30 20:00:38 EDT 2008

> >
> > 1. How do I catch the exception that is raised from "read"?
> >
> I think you want readIO, which yields a computation in the IO monad,
> so it can be caught.

Ah, that's a third option, sequence the effect using readIO,

    import System.IO
    import qualified Control.Exception as C

    main = do
        x <- getNum
        print x

    getNum :: IO Integer
    getNum = do
        y <- maybeRead
        case y of
            Nothing -> getNum
            Just n  -> return n

    maybeRead :: Read a => IO (Maybe a)
    maybeRead = C.catch
        (do x <- getLine
            n <- readIO x
            return (Just n)) -- ensure any exception is thrown here
        (const (return Nothing))

-- Don

More information about the Haskell-Cafe mailing list