On 07/16/2013 09:57 PM, Michael Orlitzky wrote:
> I have a common pattern in my command-line programs; I start out with a
> configuration data type, which over-simplified looks like:
> 
>   data Cfg = Cfg { verbose :: Bool }
> 
> Now, there's usually a default configuration,
> 
>   default :: Cfg
>   default = Cfg False
> 
> The user can override the defaults one of two ways, either via a config
> file, or from the command-line. If both are specified, the command-line
> takes precedence. The way I do this is with,
> 
>   data OptionalCfg = OptionalCfg { verbose :: Maybe Bool }
> 
> And then I define I Monoid instance for OptionalCfg which lets me merge
> two ofthem. Once the two OptionalCfgs are merged, I merge *that* with
> the default Cfg.
> 
> This all works great, except that when there's 20 or so options, I
> duplicate a ton of code in the definition of OptionalCfg. Is there some
> pre-existing solution that will let me take a Cfg and create a new type
> with Cfg's fields wrapped in Maybe?

One option is to combine OptionalCfg with Cfg, by parameterizing Cfg. If
you make

  data Cfg a = Cfg { cfgVerbose :: a Bool }

Then you can choose between Cfg Identity and Cfg Maybe. Furthermore,
these are different types, so you can still have a monoid over Cfg Maybe.

There might be some lens magic that makes working with this easier too.
For example,

  verbose :: Lens' (Cfg a) Bool
  verbose = cfgVerbose.traverse

Or something to that effect (that actually compiles).

- ollie

Attachment: signature.asc
Description: OpenPGP digital signature

_______________________________________________
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe

Reply via email to