Charles Durham
Charles Durham

Reputation: 1707

Haskell typeclasses with algebraic data types

I have some algebraic data types A, B, and C each implements the class:

class Dog a where
   dog :: a -> Bool

If I create a new algebraic data type:

data D = A | B | C

Is there an easy way to have D implement Dog without having to redefine each instance for A, B and C again?

Thanks

Upvotes: 4

Views: 322

Answers (1)

Daniel Wagner
Daniel Wagner

Reputation: 152682

Before answering, I should point out that you may be falling into a common beginner's misconception about ADT's. Remember, Haskell has two separate namespaces for the type and term levels. So if we write:

data A = Foo
data B = Bar
data C = Baz
data D = A | B | C

...then there's no connection between the type A and the constructor A of type D. Therefore I suspect (but am not totally sure!) that the question you meant to ask had the following format for type D, instead:

data D = A A | B B | C C

In this case, the short answer is "no". You might wish that you could tack on a deriving Dog or some such thing and be done, but that facility is not provided by the language. That said, there are some packages for generic programming that could help: just check the Hackage packages list and search for "deriv" and you'll get about ten hits.

Upvotes: 8

Related Questions