开发者

Haskell typeclasses with algebraic data types

开发者 https://www.devze.com 2023-03-19 23:55 出处:网络
I have some algebraic data types A, B, and C each implements the class: class Dog a where dog :: a -> Bool

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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消