Skip to content
Type Classes
step 1/5

Reading — step 1 of 5

Learn

~1 min readType Classes and Functors

A type class in Haskell is an interface — a set of operations a type must implement.

class Greet a where
    hello :: a -> String
    -- Default implementation
    shout :: a -> String
    shout x = map toUpper (hello x)

Implement with instance:

data English = English

instance Greet English where
    hello _ = "hi"

Use with type class constraints in signatures:

announce :: Greet a => a -> IO ()
announce x = putStrLn (hello x)

The Greet a => part is a constraint — "this function works on any a that has a Greet instance."

Standard type classes you'll meet constantly:

  • Show a — has show :: a -> String
  • Eq a — has ==, /=
  • Ord a — has compare, <, > (requires Eq)
  • Num a — numeric (+, -, *, negate, ...)
  • Functor f — has fmap
  • Applicative f — has pure, <*>
  • Monad m — has >>=, return
  • Foldable t — has foldr, foldl, etc.

Deriving auto-generates instances for common classes:

data Point = Point Int Int
    deriving (Show, Eq, Ord)

show (Point 3 4)        -- "Point 3 4"
Point 1 2 == Point 1 2  -- True

Haskell's type class system is the basis for its tight, polymorphic style — and the foundation for monads.

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…