liveBook · Manning

StandaloneDeriving

As explained in Learn Haskell by Example

StandaloneDeriving is a GHC language extension that permits deriving clauses and type-class instances to be declared separately from data type declarations.

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

How Learn Haskell by Example covers it

How deep it goes
Demonstrates extension syntax and concrete instances, but does not explain deriving mechanics beyond these cases.
Examples
Uses heterogeneous pitches and typed PNM images to demonstrate standalone Show and Eq instances.
What it assumes
Assumes familiarity with data declarations and type classes while introducing the need for separate deriving with existential types and GADTs.
What you can do after
Apply standalone deriving to define Show or Eq instances for existential wrappers and GADTs.
How it connects
Connects standalone deriving with existentially quantified types, GADTs, type classes, and deriving clauses.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Haskell by Example. The section links point to the parts of the book it draws on.