Haskell Type Classes Finally Clicked

Yet another post on the internet about someone thinking they figured out functional programming

4/26/2019 - Blade Chapman

So I just read this and this and something about reading them back to back finally made type classes really click for me.

First, Joe Armstrong explains

functions and data structures are completely different types of animal it is fundamentally incorrect to lock them up in the same cage.

This concept is just so fundamental to functional programming. My OO brain is always tempted to smash functions into data via methods. But by keeping them separate, we lay the foundation upon which other FP concepts like type classes can be built.

Second, A Gentle Introduction to Haskell explains that the fundamental problems type classes are trying to solve are

  1. We need a way to make a function work for many types
  2. We need a way to specify that a function (e.g. == or Eq) does not necessarily work for all types
  3. For the types that do work for a function, we need a way to customize what that function does for that type

The revelation for me is that type classes are not a way to augment data with functionality like methods augment objects in OO. Instead, they are a way to augment functions so that they can work with many different types of data. For so long I've tried to bend type classes into the model of OO inheritance because that is what's been beaten into my brain for so long. But type classes describe a relationship between data and functions that is totally inverted from traditional OO inheritance. Understanding that was the nudge that clicked type classes into place.


References: