开发者

Deriving arbitrary functions in Haskell

When working with derived instances in Haskell, is it possible to derive functions for arbitrary types, or are we restricted to particular functions?开发者_如何学Go


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.


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.


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 :-)


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.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜