Chapter Two: Type Classes

Type classes are an indefensible part of how we write Haskell. A lot of the rest of this material won't make a lot of sense without them🤪

What's in a Name?

Calling them "type classes" is both a stroke of genius and a terrible mistake. There are absolutely strong parallels with classes from object-oriented programming. They also mostly work the exact opposite way that you'd expect coming from OOP.

Abstraction

Type classes let you define a common interface across many types. The concrete function that gets called gets determined by how you define an instance of that class.

For example, let's say that you have these functions:

1

add :: Int -> Int -> Int

2

add a b = a + b

3

4

(++) :: [a] -> [a] -> [a]

5

[] ++ bs = bs

6

(a : as) ++ bs = a : as ++ bs

7

8

append :: Text -> Text -> Text

9

append a b = -- Long complex function

10

11

-- Function composition

12

(.) :: (b -> c) -> (a -> b) -> (a -> c)

13

f . g = \x -> f (g x)

Copied!

In a sense, all of these do the same thing: they combine values of a common type together (i.e. they all have the form a -> a -> a) While we may expect them to behave in some common ways, the exact meaning of that depends on the specific type. Why not write functions that could work on any of these types with respect to this combining behaviour?

We can define a common interface for this "combinable" behaviour!

1

class Combinable a where

2

combine :: a -> a -> a

Copied!

This is called a semigroup in maths, so the version in the library is actually called Semigroup. Don't let the math-y name scare you! It's actually very straightforward for a "combinable" thing.

1

class Semigroup a where

2

(<>) :: a -> a -> a

Copied!

Let's write some instances!

1

instance Semigroup Int where

2

a <> b = a + b

3

4

instance Semigroup [a] where

5

as <> bs = as ++ bs

6

7

instance Semigroup Text where

8

a <> b = append a b

Copied!

Finally, let's use it in a function. We place "class constraints" before the arguments in the type signature, separated by a =>.

1

triple :: Semigroup a => a -> a

2

triple x = x <> x <> x

3

4

triple 10

5

-- 30

6

7

triple [1, 2, 3]

8

-- [1, 2, 3, 1, 2, 3, 1, 2, 3]

9

10

triple "hi"

11

-- "hihihi"

12

13

(triple (*2)) 5

14

-- 40

Copied!

Libraries tend to give you a lot of "functions for free" to go with your instance. It's typically worth it to define an instance for a new data type.

Recursive Abstraction

It's Roughly Like Inheritance™

Unlike OO where inheritance happens on concrete data, Haskell's "inheritance" on interfaces is more like saying "assuming that you have an x, then you can also do y!" It lets you extend abstract interfaces with more functions. This usually makes for a smaller number of types that have the new interface, because they need the old type class, plus an instance for the new one, which is not always even possible!

Let's extend that Semigroup to have an element that when used with <> is a no op. We'll call this mempty, because of how it works on lists ([] ++ xs = xs) and because the name id was already taken.

1

class Semigroup a => Monoid a where

2

mempty :: a

Copied!

By definition, a Monoid is assumed to have a Semigroup instance kicking around. It has both mempty and <> automatically available. Let's look at a few of these:

1

intance Monoid Int where

2

mempty = 0

3

4

instance Monoid [a] where

5

mempty = []

6

7

instance Monoid Text where

8

mempty = ""

9

10

instance Monoid (-> a) where

11

mempty = id

Copied!

Functor Hierarchy

The most widely-used type class heirarchy is the Functor tree, which includes the infamour Monad class. These also have special rules that you need to obey when writing instances for, but you'll mostly be using someone else's so don't worry about them too much for now.

There's also highly-recommended visual guide for the following material at Functors, Applicatives, And Monads In Pictures.

Functor

You may not know it, but you're already familair with functors!

1

class Functor where

2

fmap :: (a -> b) -> f a -> f b

Copied!

You'll see a lot of fmap's operator variants <gt; and <&> floating around

1

fmap show [1,2,3] -- ["1", "2", "3"]

2

show <gt; [1,2,3] -- ["1", "2", "3"]

Copied!

The pun here is that it's the same as $ (application) but working on something that's been put into a container (practically any sum or product type), hence the visual pun of <gt;. Same goes for & (pipe) and <&>.

1

show $ 1 -- "1"

2

show <gt; [1, 2, 3] -- ["1", "2", "3"]

3

4

1 & show -- "1"

5

[1, 2, 3] <&> show -- ["1", "2", "3"]

Copied!

Applicative Functor

Applicatives add a lot of power to Functors by defining two functions:

1.

pure (also known as the somewhat confusingly named return) takes a plain value and wraps it in a container.

2.

<*> does function application when both functions and arguments are wrapped

1

class Functor f => Applicative f where

2

pure :: a -> f a

3

(<*>) :: f (a -> b) -> f a -> f b

Copied!

The <*> is often referred to as the Tie Fighter operator 🤣 It's also called ap, short for "applicative apply".

For example, on Maybe:

1

instance Applicative (Maybe a) where

2

pure x = Just x

3

4

Just f <*> Just x = Just $ f x

5

_ <*> _ = Nothing

6

7

pure 4 :: Just Int -- Just 4

8

pure "hi" :: Just Text -- Just "hi"

9

10

Just (*10) <*> Just 6 -- Just 60

11

Nothing <*> Just 6 -- Nothing

12

Just (*10) <*> Nothing -- Nothing

Copied!

Monad

1

class Applicative m => Monad m where

2

(>>=) :: m a -> (a -> m b) -> m b

3

join :: m (m a) -> m a

Copied!

>>= is pronounced "bind". This is because when you use it to link into the next function, it "binds" to the first argument, like a supercharged pipe. Further, because of how scoping rules work, argument name bindings last until the end of the chain:

1

[1,2,3] >>= \a ->

2

[a + 1] >>= \b ->

3

[(show b, a * 10)]

4

-- [("2", 10), ("3", 20), ("4", 30)]

Copied!

There's also an inverted bind operator, =<< with arguments reversed

Let's look at a couple instances:

1

instance Monad [a] where

2

join xs = foldr (++) [] xs

3

xs >>= f = join (f <gt; xs)

4

5

instance Monad (Maybe a) where

6

join Nothing = Nothing

7

join (Just inner) = inner

8

9

Nothing >>= f = Nothing

10

Just x >>= f = Just (f x)

Copied!

>>= is special compared to <gt; and <*>. It doesn't run out of arguments, and can be chained forever.

1

[1,2,3] >>= \a ->

2

pure (a + 1) >>= \b ->

3

pure (b * 10) >>= \c ->

4

pure (c - 5)

5

-- [15, 25, 35]

Copied!

It can also be used to change behaviour, changing its structure based on arguments:

1

[1,2,3] >>= \a ->

2

if rem a 2 == 0 then [a + 1] else [a, a * 2, a * 3] >>= \b ->

3

if b > 10 then [a] else [b]

4

-- [1, 2, 3, 3, 3, 6, 9]

5

6

Just 42 >>= \a ->

7

if a > 10 then Nothing else Just a >>= \b ->

8

Just (b * 10) >>= \c ->

9

Just (show c)

10

-- Nothing

Copied!

Do Notation

Above there's a lot of >>= and nesting to keep it straight. Haskell has "do notation" to clean this up, make it feel like an linear set of instructions, and also pun on a lot of imperative programming.

When using do notion, we often replace pure with return, which is the same function but renamed for extra imperative punning.

return does not exit out of the function chain. It is the same function as pure and only wraps values in the correct container.

Bind

Do Notation

1

[1,2,3] >>= \a ->

2

pure (a + 1) >>= \b ->

3

pure (b * 10) >>= \c ->

4

pure (c - 5)

Copied!

1

do

2

a <- [1, 2, 3]

3

b <- return $ a + 1

4

c <- return $ b * 10

5

return $ c - 5

Copied!

There's also a special variant of let that lets you skip the <- for simple values.

Without Let

With Let

1

do

2

a <- [1, 2, 3]

3

b <- return (a * 10)

4

return (b + 1)

Copied!

1

do

2

let as = [1, 2, 3]

3

let b = fmap (*10) as

4

return (b + 1)

Copied!

Cheat Sheet

How these all relate to each other can be hard to keep straight at first. Here's a handy guide in pseudocode:

1

-- WARNING: Abuse of notation!

2

3

(a -> b) $ a == b -- Plain function

4

(a -> b) <gt; m a == m b -- Functor

5

m (a -> b) <*> m a == m b -- Applicative

6

(a -> m b) =<< m a == m b -- Monad

7

8

{-| Legend

9

a is a value

10

b is a value

11

m is a data wrapper / container

12

-}

Copied!

The Orphanage

For the compiler to know that there are not duplicate, conflicting instances for type classes, instances need to be written in the same module as the class declaration, or in the same module as a datatype definition. But what happens when you need to add an instance from a library to a datatype that's also from a library?

These are called type class "orphans," and we shove isolate them in a module (or submodules) called Fission.Internal.Orphanage. Importing this module doesn't have any actual exports, but you do need to signal to the compiler that it's a dependency for the module that you're writing. Importing it normally will lead to the linter complaining about an unused import. You can get around this warning by explicitely showiung that are no imports:

1

import Fission.Internal.Orphanage ()

Copied!

The downside to having all of your orphan instances in a single module is that it progressivbley slows your compile times down after touching the orphanage because it need to check every module that imports it for new instances. As this file grows, it is typically a good idea to break it into submodules, and only import the orphan modules that you actually need in each scenario.

Last modified 1yr ago