HiveBrain v1.2.0
Get Started
← Back to all entries
patternMinor

How does Bifunctor in Haskell work?

Submitted by: @import:stackexchange-cs··
0
Viewed 0 times
howworkbifunctorhaskelldoes

Problem

I was reading 'Category Theory for Programmers' by Bartosz Milewski and got really confused by the implementation of bimap in Bifunctor typeclass.

class Bifunctor f where
    bimap :: (a -> c) -> (b -> d) -> f a b -> f c d 
    bimap g h = first g . second h
    first :: (a -> c) -> f a b -> f c b
    first g = bimap g id
    second :: (b -> d) -> f a b -> f a d
    second = bimap id


This is the definition of the Bifunctor typeclass taken directly from the library Control. If bimap evaluates to first and second, which in turn evaluates to bimap itself, how is this supposed to end? Could you please explain how the evaluation of bimap works? Thank you!

Solution

A Haskell type class defines a set of functions (sometimes called methods) that belong to the type class. In most cases, specific instances must supply specific implementations of one or more of these.

An instance can implement all methods, or just enough to make the instance work. If an instance doesn't implement all methods, the default implementations are used.

Type classes are typically documented with the minimal implementation required. This is also true for Bifunctors:

Minimal complete definition

bimap | first, second


This means that an instance must implement either bimap, or both first and second. An instance can also implement all three, but that's not required.

The tuple instance, for example, is implemented using bimap:

instance Bifunctor (,) where
  bimap f g ~(a, b) = (f a, g b)


This means that the first and second implementations are the default implementations you quoted above. They call the instance's bimap implementation.

Code Snippets

Minimal complete definition

bimap | first, second
instance Bifunctor (,) where
  bimap f g ~(a, b) = (f a, g b)

Context

StackExchange Computer Science Q#118703, answer score: 5

Revisions (0)

No revisions yet.