[Haskell-cafe] GetOpt

Einar Karttunen ekarttun at cs.helsinki.fi
Wed Apr 26 19:26:22 EDT 2006


On 26.04 11:29, Anton Kulchitsky wrote:
> I just started to study Haskell and it is my almost first big experience 
> with functional languages (except Emacs Lisp and Python). I enjoyed all 
> small exercises and started a bigger business writing a general utility. 
> However, I have a problem from the beginning. The utility get some file 
> and convert it to another format. It is a kind of small compiler. It 
> also accepts many parameters and behaves depending on them. The problem 
> is how to do this neat! How should I write my program to accept and 
> neatly work with options????

One solution is to have a datatype for configuration:

> data Config = Config { mode    :: Mode,
>                        infile  :: Maybe FilePath,
>                        outfile :: Maybe FilePath
>                      }
> nullConfig = Config Normal "-" "-"
> data Mode   = Normal | Version | Help

and handle options as functions from Config to Config:

> Option ['i']   ["input"]   (ReqArg (\x c -> c { infile = Just x }) "file") "input file name"

and then handle the parsed options like:

> case conf of
>   Config Normal (Just i) (Just o) -> ...
>   Config Normal _        _        -> both input and output must be specified
>   Config Help   _        _        -> help message

- Einar Karttunen



More information about the Haskell-Cafe mailing list