[Haskell-cafe] Read instance for constructors?

Semen Trygubenko / Семен Тригубенко semen at trygub.com
Tue Mar 11 12:08:29 UTC 2014


On Mon, Mar 10, 2014 at 10:47:26PM +0000, gb wrote:
> 
> > 
> > Great! But how do I recover the actual constructor? E.g., 
> > 
> > f :: String -> Constr
> > f s = fromMaybe (error "error in f") $ readConstr (dataTypeOf $ B 1) s
> > 
> > gives me back Data.Data.Constr (not D). I was hoping for something along 
> the lines
> > 
> > f "A" $ 1
> > 
> > to get back a value
> > 
> > A 1
> > 
> > of type D, etc.
> > 
> > Many thanks,
> > S.
> > 
> 
> Here's one way: 
> 
> import qualified Data.Generics.Builders as B
> import Data.Generics.Aliases 
> 
> fromConstrB (B.empty `extB` (12::Int)) (f "B")::D
> >>> B 12
> 
> fromConstrB B.empty (f "B")::D
> >>> B 0

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.



-- 
Семен Тригубенко http://trygub.com
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 196 bytes
Desc: not available
URL: <http://www.haskell.org/pipermail/haskell-cafe/attachments/20140311/69470959/attachment.sig>


More information about the Haskell-Cafe mailing list