Questions relating to the automated process of deriving typeclass instances for particular classes or types, such as using the "deriving" keyword in Haskell or the "derive" macro in Rust.
Typeclass resolution is a process available in several languages, most notably Haskell and Rust, by which polymorphic functionality can be provided in an ad-hoc way to several types.
Writing instances for these types can become tedious in some cases where large amounts of predictable boilerplate can be possible. For instance, the Eq
typeclass in Haskell compares two values to determine if they're equal, and it is very common to implement this typeclass by simply comparing each field of the two values for equality recursively.
For classes like this, languages often provide a "deriving" mechanism by which the intuitive, default behavior can be "opted into".
data MyCustomType = MyCustomType Int String
deriving (Eq)
In this Haskell example, we define a type called MyCustomType
which contains an integer and a string. Then we "derive" the Eq
instance in the default way. This is equivalent to the longer, more verbose
data MyCustomType = MyCustomType Int String
instance Eq MyCustomType where
MyCustomType n s == MyCustomType n' s' = n == n' && s == s'
In cases where something unusual needs to be done, the full instance can still be written out.
This tag should be used for questions about the mechanism by which instances are derived in languages that provide this ability.