[Haskell-cafe] Avoiding boilerplate retrieving GetOpt cmd line args

Levi Stephen levi.stephen at optusnet.com.au
Fri Jul 27 01:31:04 EDT 2007


Hi,

Not sure if this will help avoid the boilerplate, but I've always liked 
the approach at 
http://leiffrenzel.de/papers/commandline-options-in-haskell.html 
(particularly the section "Towards a higher level") for being able to 
specify defaults. It's the best resource I've found on command line 
options in Haskell so far.

Levi
> Ok, I'm writing a command line tool, using System.Console.GetOpt to 
> handle command line arguments. My Flags structure so far is
>
>> data Flag
>>     = Filter String
>>     | DateFormat String
>>     | DocStart String
>>     | DocEnd String
> ...
>
> and I want to write accessor functions that return the strings if 
> specified, otherwise returning a default. The best I've been able to 
> do is this:
>
>> getFilter = getString f "Markdown.pl"
>>     where f (Filter s) = Just s
>>           f _ = Nothing
>>
>> getDateFormat = getString f "%B %e, %Y"
>>     where f (DateFormat s) = Just s
>>           f _ = Nothing
>>
>> getDocStart = getString f "^{-$"
>>     where f (DocStart s) = Just s
>>           f _ = Nothing
>>
>> getDocEnd = getString f "^-}$"
>>     where f (DocEnd s) = Just s
>>           f _ = Nothing
>
> using a generic accessor function `getString`.
>
> There are eight (and growing) needless lines here, where what I really 
> want to do is to pass the constructors `Filter`, `DateFormat`, 
> `DocStart`, or `DocEnd` to the function `getString`. ghci types each 
> of these as `String -> Flag`, so one at least knows how to type such a 
> `getString`, but using a constructor-passed-as-an-argument in a 
> pattern match is of course a "Parse error in pattern". (I expected as 
> much, but I had to try... `String -> Flag` is not enough information 
> to make it clear we're passing a constructor, rather than some hairy 
> arbitrary function, so such a pattern match would be undecidable in 
> general.)
>
> So what's the right idiom for avoiding this boilerplate?
>
> Thanks,
> Dave
>
> _______________________________________________
> Haskell-Cafe mailing list
> Haskell-Cafe at haskell.org
> http://www.haskell.org/mailman/listinfo/haskell-cafe



More information about the Haskell-Cafe mailing list