Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 290
Charles Durham Avatar asked Feb 23 '23 14:02

Charles Durham


1 Answers

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.

like image 50
Daniel Wagner Avatar answered Feb 27 '23 16:02

Daniel Wagner