liveBook · Manning

DeriveAnyClass

As explained in Learn Haskell by Example

DeriveAnyClass is a GHC language extension that permits automatic derivation of type-class instances when their minimal definitions are empty.

DeriveAnyClass is a GHC language extension that lets the compiler create a type-class instance when the class has no minimal definitions to implement. Enable it when declaring a type that should receive such an instance automatically. section 14.4 section 14.5

Deriving an Exception instance

Enable the extension and derive both Show and Exception for a custom error type:\n\n:set -XDeriveAnyClass\ndata SomeFailure = SomeFailure String deriving (Show, Exception)\n\nThe resulting value can be thrown and caught with Control.Exception functions such as throw and catch. section 14.4

class (Typeable e, Show e) => Exception e where
  toException :: e -> SomeException
  fromException :: SomeException -> Maybe e
  displayException :: e -> String

The Exception class shows why derivation works here: its displayed class definition has required methods, but the treatment identifies it as having no minimal definition. section 14.4

How Learn Haskell by Example covers it

How deep it goes
Explains the empty-minimal-definition rule and demonstrates extension activation, derivation, throwing, and catching.
Examples
Uses SomeFailure with a String payload and demonstrates deriving Show and Exception in GHCi.
What you can do after
Build it from scratch by enabling DeriveAnyClass and deriving a usable Exception instance for a custom type.
How it connects
Connects type-class derivation with Exception, SomeException, throw, and catch.

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.