When working with derived instances in Haskell, is it possible to derive functions for arbitrary types, or are we restricted to particular functions?

- 137,316
- 36
- 365
- 468

- 114,675
- 90
- 247
- 350
-
2Hehe, +1 if you found this because you were hoping you could derive `Test.QuickCheck.Arbitrary` for ADTs. :) – Jason Orendorff Nov 25 '13 at 16:10
4 Answers
You can derive instances of the following classes in haskell 98: Eq, Ord, Enum, Ix, Bounded, Read, and Show.
Using ghc extensions you can also derive instances of the following classes: Typeable, Data, Functor, Foldable and Traversable. There's also a ghc extension that allows a newtype to derive instances from its implementation type.
You can not derive instances of arbitrary classes for the simple reason that haskell would not know how to generate the necessary functions without special knowledge about the class in question.

- 363,768
- 54
- 674
- 675
-
But GHC can handle some simple cases. If you say `newtype Bar = Bar Foo` and Foo has a Quux instance, then GeneralizedNewtypeDeriving can derive the Quux instance for Bar for you. Of course, this is just trivial unwrapping, but it is better than nothing. – jrockway Mar 13 '10 at 04:59
You are restricted to particular classes, in terms of what the compiler knows how to derive for you. Using a preprocessor, or Template Haskell, you can yourself code up new deriving mechanisms, if you know of general approaches to yielding implementations of functions for particular types.

- 137,316
- 36
- 365
- 468
The other two answers are correct. But if you need more, there are some packages on hackage that can handle more. I like Data.Derive a lot, since you can generate the source code directly (for compatibility) or hook it into Template Haskell to do it at compile time. A wide range of classes are already supported, and it is very easy to add support for your own. Summary: advertising pitch for a damn fine library :-)

- 59,485
- 12
- 145
- 204
-
I now take this back. I hadn't at the time tried to add support for my own, but I assumed it was easy. It isn't; it involves recompiling the library from what I can tell. But still the built-in support is nice and complete. – luqui Apr 21 '11 at 19:50
To add to Don's answer: deriving custom functionality for datatypes is called generic programming and there is a lot of literature about this. Preprocessors and Template Haskell are not the only solutions; see one of the overview papers that list of literature for other options.

- 6,713
- 3
- 31
- 38