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
