@hackage simpleargs0.2.1

Provides a more flexible getArgs function with better error reporting.

SimpleArgs - provide a more flexible and informative replacement for getArgs

For "real" command line programs, you usually want to provide a flexible command line with various options and settings, sensibly named and with auto-generated help. In that case, SimpleArgs is not for you, stop reading this, and look up System.Console.GetOpt¹ instead.

But sometimes, a quick hack is just what you need. Previously, you were wont to do:

main = do
    [count',gender'] <- getArgs
let count = read count
    gender = case gender' of 
       	      	     "M" -> 'M'
		     "F" -> 'F'
main_real count gender

This is somewhat tedious, wastes precious sceen estate, users supplying parameters of the wrong type will get obscure errors, and while any programming errors you might introduce probably will be trivial, it would be better to avoid them entirely.

The SimpleArgs module provides getArgs with an overloaded return type, so that command line parameters are parsed as the types required by the rest of the program.

Using SimpleArgs, the above could therefore look like this:

main = do 
    (count,gender) <- getArgs
    main_real count gender

or even (I think):

main = getArgs >>= return . uncurry main_real

If that was a bit contrieved, let's say you just want to read a file name:

 main = do
    [filename] <- getArgs
    readFile filename >>= print . length 

I'm sure you could avoid the information-free name "filename" by some esoteric tranformation to more point-free style, but I argue that SimpleArgs makes this natural and easy:

main = getArgs >>= readFile >>= print . length

I don't think 'wc -c' gets much easier than this. Here's a custom data type (which is parsed using its Read instance, and also needs Typeable):

import System.SimpleArgs
import Data.Typeable

data Gender = Male | Female deriving (Typeable,Read)

main = do
    g <- getArgs
    case g of Male -> putStrLn "X and Y"
              Female -> putStrLn "two Xs"

Instead of reporting errors rather anonymously as incomplete cases or read failures, SimpleArgs will provide more sensible error reporting. (To try this, build Example by executing 'ghc --make Example.hs'). It will:

  1) report incorrect number of parameters,
  	 also mentioning the expected parameters and types:

  % ./Example foo
  Example: Incorrect number of arguments, got 1,
  expected 2 (Int,[Char])

This also gives you a useful hint if you just run the program
without any parameters.

  2) report parameters that fail to parse as the required type:

      % ./Example foo 10
  Example: Couldn't parse parameter "foo" as type Int

Nice, huh? Please enjoy, and let me know how you fare at ketil@malde.org.

¹ http://www.haskell.org/haskellwiki/High-level_option_handling_with_GetOpt