Haskell in Depth cover
welcome to this free extract from
an online version of the Manning book.
to read more
or

2 Type classes

 

This chapter covers

  • Exploiting type classes as tools for writing code that works for values of different types
  • Considering type classes as a concept applicable to many types
  • Using basic type classes defined in the standard library
  • Abstracting computations via type classes

Haskell programmers tend to write code that can be reused in many ways. To achieve that, they avoid using specific types while writing code and use type variables instead. Depending on the types, the actual code may differ. This is possible thanks to type classes and their instances.

Type classes are usually considered Haskell’s most prominent feature. They originated in Haskell and were then taken up by other programming languages. A type class is defined with respect to some type variable. It contains a collection of methods, given by type signatures. We can define as many instances, or implementations, for specific types as we need.

Writing functions with respect to a type class, as opposed to using concrete types, allows you to be more general: a function will work with different types, even if they don’t exist at the time of declaring a type class. This makes type classes especially useful for libraries because we don’t know in advance which user-defined types will be used with our library in the future.

2.1 Manipulating a radar antenna with type classes

2.1.1 The problem at hand

2.1.2 Rotating a radar antenna with Eq, Enum, and Bounded

2.1.3 Combining turns with Semigroup and Monoid

2.1.4 Printing and reading data with Show and Read

2.1.5 Testing functions with Ord and Random

2.2 Issues with numbers and text

2.2.1 Numeric types and type classes

2.2.2 Numeric conversions

2.2.3 Computing with fixed precision

2.2.4 More about Show and Read

2.2.5 Converting recursive types to strings

2.3 Abstracting computations with type classes

2.3.1 An idea of a computational context and a common behavior

2.3.2 Exploring different contexts in parallel

2.3.3 The do notation

2.3.4 Folding and traversing

Summary

sitemap