[Haskell-cafe] Wrapping all fields of a data type in e.g. Maybe
Oliver Charles
ollie at ocharles.org.uk
Wed Jul 17 00:21:30 CEST 2013
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
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 490 bytes
Desc: OpenPGP digital signature
URL: <http://www.haskell.org/pipermail/haskell-cafe/attachments/20130716/3a038dc0/attachment.pgp>
More information about the Haskell-Cafe
mailing list