[Haskell-cafe] No instance for (Constructor Main.D1MyData)

Maarten Faddegon haskell-cafe at maartenfaddegon.nl
Tue Dec 10 15:48:57 UTC 2013

Dear list,

I try to implement the generic show of section 3.6 from the paper 
Magelheas et al., "A Generic Deriving Mechanism for Haskell" but run 
into problems with the Constructor class. If someone could point out 
what is wrong here I would be most grateful.

I import generics:

> import GHC.Generics

And I define my own "Show" class named "Toonbaar", and a generic version 
of the class "GToonbaar":

> class Toonbaar a where
>         toon :: a -> String
>         default toon :: (Generic a, GToonbaar (Rep a)) => a -> String
>         toon a = gtoon (from a)
> instance Toonbaar Int where
>         toon i = show i
> class GToonbaar f where
>         gtoon :: f a -> String

Next I want implement instances of gtoon for the 5 primitive types that 
are used to by the "from" function to represent data types. Most 
interisting is the meta-information instance here, where I use the
"conName" function.

Most of the rest I copied from the serialization example on the wiki: 

> -- | Meta-information (constructor names, etc.)
> instance (GToonbaar a, Constructor c) => GToonbaar (M1 i c a) where
>         gtoon m@(M1 _) = conName m
> -- | Unit: used for constructors without arguments
> instance GToonbaar U1 where
>         gtoon _ = "Unit"
> -- | Constants, additional parameters and recursion of kind *
> instance (GToonbaar a, GToonbaar b) => GToonbaar (a :*: b) where
>         gtoon _ = "Constant"
> -- | Sums: encode choice between constructors
> instance (GToonbaar a, GToonbaar b) => GToonbaar (a :+: b) where
>         gtoon x = gtoon x
> -- | Products: encode multiple arguments to constructors
> instance (Toonbaar a) => GToonbaar (K1 i a) where
>         gtoon (K1 x) = toon x

I define a data type, deriving Generic and make it an instance of Toonbaar.

> data MyData = MyInt Int
>             deriving (Generic)
> instance Toonbaar MyData
> main = putStrLn (toon (MyInt 42))

When I try to compile the above, ghc emits the following error:

     No instance for (Constructor Main.D1MyData)
       arising from a use of `Main.$gdmtoon'
     Possible fix:
       add an instance declaration for (Constructor Main.D1MyData)
     In the expression: (Main.$gdmtoon)
     In an equation for `toon': toon = (Main.$gdmtoon)
     In the instance declaration for `Toonbaar MyData'

There are 2 things here that I do not understand:

1. I was under the impression that Constructor can be derived, but this 
does not seem to be the case. (I tried adding it to the line where I 
also derive Generic). Is there another way to derive it?

2. Why is the error message referring to D1MyData and not to MyData? And 
$gdmtoon instead of toon or gtoon?



More information about the Haskell-Cafe mailing list