liveBook · Manning

Type-class instance

As explained in Learn Haskell by Example

A type-class instance is a declaration that supplies an implementation of a type class's operations for a particular type.

A type-class instance supplies implementations of a type class's operations for a particular type. It connects general operations with concrete data types. section 5.1.3

An instance may implement only the class's minimal method when other methods have default implementations. Type constraints allow instances to compose, such as Eq a => Eq (Maybe a). section 5.1.3 section 7.4.1

Common instance patterns include:

  • Declare an Eq instance to compare values of a type using == and /=. section 5.1.3
  • Define Sliceable [a] by implementing slicePartition; derive slice from the class default. section 7.4.1
  • Lift an instance through a type constructor, as Sliceable a => Sliceable (Maybe a). section 7.4.1
  • Use Generic derivation to provide empty ToJSON and FromJSON instances for a data type. section 16.2

Slicing lists through an instance

instance Sliceable [a] where slicePartition idx1 idx2 xs = (take idx1 xs, take (idx2 - idx1) (drop idx1 xs), drop idx2 xs) This supplies slice automatically, so slice 2 8 [0..9] produces [2,3,4,5,6,7]. section 7.4.1

Listing 16.4 A ToJSON instance for TodoEntry
{-# LANGUAGE DeriveGeneric #-}  #1

module Todos.Types where

import qualified Data.Aeson as J    #2
import qualified Data.Text as T     #2
import GHC.Generics (Generic)  #3

data TodoEntry = TodoEntry  #4
  { entryId :: Maybe Int,
    text :: T.Text,
    checked :: Bool,
    rank :: Maybe Int
  }
  deriving (Eq, Show, Generic)  #5

instance J.ToJSON TodoEntry      #6

instance J.FromJSON TodoEntry   #6

A compact derived-instance example shows Generic, ToJSON, and FromJSON working together for TodoEntry. section 16.2

How Learn Haskell by Example covers it

How deep it goes
Defines minimal methods, defaults, constraints, delegation, and deriving, but defers generic representation internals.
Examples
Uses Eq for comparisons, Sliceable for lists, Maybe, and CSV tables, and Generic for TodoEntry JSON roundtrips.
What it assumes
Assumes basic Haskell types and functions while teaching type classes, constraints, defaults, and deriving through examples.
What you can do after
Build it from scratch by implementing minimal class methods and reuse defaults across lists, Maybe values, and custom data types.
How it connects
Relates type classes to type constraints, default methods, generic programming, JSON serialization, and algebraic data types.

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.