[Haskell-beginners] how to access command line arguments

Antoine Latter aslatter at gmail.com
Sat Aug 14 23:59:32 EDT 2010


On Sat, Aug 14, 2010 at 10:39 PM, prad <prad at towardsfreedom.com> wrote:
> here's one way:
>
> import System (getArgs)
>
> args <- getArgs
>
> first = head args
> last  = last args
> and so on.
>
> i can also do this
>
> (first:last:z) <- getArgs
>
> and avoid using head and tail. in fact, this seems nicer because i can
> pattern match for a specific series of inputs. however, if the inputs
> aren't there (eg say program arg1 only instead of program arg1 arg2),
> then the runtime pattern match failure error:
>
> user error (Pattern match failure in do expression at Tests.hs:14:4-14)
>
> is understandably generated. this of course doesn't happen if i just
> use args because there is no pattern matching.
>
> is the former the better way to do it then? or are there other
> alternatives?
>

For really simple uses, you can always do something like:

> getMyArgs :: IO (Maybe SomeDataTypeYouWant)
> getMyArgs
>  = do
>  args <- getArgs
>  case args of
>     [pattern, you, want] -> Just $ <parse arguments>
>     _  -> Nothing

Then you can cleanly handle the 'Nothing' case and do whatever is
appropriate for not having arguments.

For more complicated cases, GHC ships with this module for processing
command line arguments:

http://haskell.org/ghc/docs/6.12.1/html/libraries/base-4.2.0.0/System-Console-GetOpt.html

There are also a few packages on hackage:

cmdargs, which is targeted towards programs with multiple operating
modes which have different options:
http://hackage.haskell.org/package/cmdargs

parseargs:
http://hackage.haskell.org/package/parseargs

cmdlib is newer - I haven't seen a release announcement for it, so I
don't know what sets it apart:
http://hackage.haskell.org/package/cmdlib

Antoine


More information about the Beginners mailing list