[Haskell-cafe] Safe way to parse arguments?

Don Stewart dons at galois.com
Sat Jun 21 15:19:32 EDT 2008


xj2106:
> Hi,
> 
> I'm wondering how usually you parse command line arguments
> list safely.  If the given argument is wrong, the program
> can still print out some error information instead of giving
> something like
> 
> Prelude.read: no parse
> 
> Let's make the discussion concrete.  Suppose we have the
> following code.
> 
> -->8----------8<--
> import System.Environment
> 
> data Conf = Conf { number :: Int }
> 
> parseArgs [] = error "need at least one argument"
> parseArgs (x:_) = Conf { number = read x }
> 
> work (Conf { number = n }) = n * (n-1) `div` 2
> 
> main = print . work . parseArgs =<< getArgs
> -->8----------8<--
> 
> If the "read x" fails in line 8, the program dies with
> 
> Prelude.read: no parse
> 
> What is the standard way to make the error message useful?
> 
> Xiao-Yong
> -- 

The main thing is to define a safe read. This will be in the base
library soon,

      maybeRead :: Read a => String -> Maybe a
      maybeRead s = case reads s of
          [(x, "")] -> Just x
          _         -> Nothing

Then you can pattern match on the failure case as Nothing.

Cheers,
  Don


More information about the Haskell-Cafe mailing list