Lesson 14. Using type classes

 

After reading lesson 14, you’ll be able to

  • Implement your own type classes
  • Understand polymorphism in Haskell
  • Know when to use deriving
  • Search for documentation with Hackage and Hoogle

In lesson 13, you got your first look at type classes, which are Haskell’s way of grouping types by common behaviors they share. In this lesson, you’ll take a deeper look at how to implement existing type classes. This will allow you to write new types that take advantage of a wide range of existing functions.

Consider this

You have a data type consisting of data constructors for New England states:

data NewEngland = ME | VT | NH | MA | RI | CT

You want to be able to display them by their full name by using Show. You can easily display their abbreviations by deriving show, but there’s no obvious way to create your own version of show. How can you make your NewEngland type display the full state name by using show?

14.1. A type in need of classes

You’ll start by modeling a six-sided die. A good default implementation is a type similar to Bool, only with six values instead of two. You’ll name your data constructors S1 through S6 to represent each of the six sides.

Listing 14.1. Defining the SixSidedDie data type

14.2. Implementing Show

14.3. Type classes and polymorphism

14.4. Default implementation and minimum complete definitions

14.5. Implementing Ord

14.6. To derive or not to derive?

14.7. Type classes for more-complex types

14.8. Type class roadmap

Summary

sitemap