StandaloneDeriving is a GHC language extension that lets deriving clauses and type-class instances appear separately from a data type declaration. It is especially useful when ordinary deriving syntax cannot handle existentially quantified types or GADTs. section 11.1.2 section 13.1.3
Enable the extension and write each derived instance as its own declaration:
- Existential wrapper: define `data Pitch = forall a. (Pitchable a, Show a) => Pitch a`, then derive `Show` with `deriving instance Show Pitch`. section 11.1.2
- GADT: define `PnmImage px` with constructors carrying different pixel types, then write `deriving instance (Show px) => Show (PnmImage px)` and the corresponding `Eq` instance. section 13.1.3
Listing 11.1 A data type for structuring notes
data Pitch = forall a. (Pitchable a, Show a) => Pitch a #1 deriving instance Show Pitch #2 instance Pitchable Pitch where toFrequency (Pitch p) = toFrequency p #3
Inspect a complete existential `Pitch` definition, its standalone `Show` instance, and its `Pitchable` implementation. section 11.1.2
Listing 13.5 Deriving type class instances for a GADT
{-# LANGUAGE StandaloneDeriving #-} #1
...
deriving instance (Show px) => Show (PnmImage px) #2
deriving instance (Eq px) => Eq (PnmImage px) #3
Inspect standalone `Show` and `Eq` declarations for a GADT indexed by pixel type. section 13.1.3
