[Haskell-cafe] Read instance for constructors?

Niklas Haas haskell at nand.wakku.to
Tue Mar 11 12:21:01 UTC 2014


> Thank you very much — it works! [and many new useful functions discovered along the way :-)].
> 
> I'm fairly happy with this solution (using readConstr as suggested by Niklas,
> and fromConstrB, as per above). The only wrinkle now is with this term in the definition of f :
> 
> dataTypeOf $ B 1
> 
> We provide a value here (B 1) — is there a way to make it take the constructor (B)
> instead, or, alternatively, make f aware of the signature of the constructor (Int -> D) and/or the resulting
> data type (D) somehow? I've hoogled it and also looked through Data.Data with no luck…
> 
> It's just that constructing a full-blown value of type D might be non-trivial if D is complex,
> but it seems a bit wasteful as we are after the outer constructor alone.
> And of course, if D or types D depends on change we need to modify f…
> 
> Thank you,
> S.

The idiomatic way to handle this kind of stuff normally is to pass an
abstract proxy that carries the type as a type argument, rather than
passing a value of that type itself, eg.:

> data Proxy a = Proxy
>
> dataTypeOf :: Data a => Proxy a -> DataTypeOf

or even a more polymorphic version:

> dataTypeOf :: Data a => f a -> DataTypeOf

which can be instantiated at any ‘f’, including Proxy, [], Maybe or
others.

Unfortunately, it does not seem that Data.Data.Data has gone for this
route, so my feedback is a bit useless. You could still provide your own
wrapper function (that uses ‘undefined’ internally, which we know here
to be safe even though it's ugly), though.


More information about the Haskell-Cafe mailing list