[Haskell-cafe] Safe way to parse arguments?

Xiao-Yong Jin xj2106 at columbia.edu
Sat Jun 21 15:12:38 EDT 2008


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
-- 
    c/*    __o/*
    <\     * (__
    */\      <


More information about the Haskell-Cafe mailing list