20 Category theory
Lesson goal Understand what a category is in programming, with types as objects and functions as morphisms, and which two laws their composition obeys.
There is a close connection between functional programming and category theory. In functional programming many abstractions, laws and principles are taken from category theory.
So what do we know about category theory? We will not dive into the fundamentals and academic terms. We will try to explain all of this without academic terminology.
A category, in the context of programming, is a collection of objects (data types: Array, Object, Number, String, ...) and morphisms between them (arrows, that is, functions). Morphisms f :: a -> b and g :: b -> c can be composed into g . f :: a -> c (read as "g after f": first f, then g). Composition obeys two laws. Identity: every object has an identity morphism id :: a -> a, and composing with it changes nothing (f . id = f, id . f = f). Associativity: h . (g . f) = (h . g) . f, so it does not matter where the parentheses go.
// Example
// f :: a -> b
// g :: b -> c
// g . f :: a -> c
// a, b, c are objects (types)
// f, g are morphisms (arrows), that is, functions
// g . f is composition: first f, then g
// A practical example
// concatX :: Number -> String
const concatX = num => `${num} X`
// toArray:: a -> [a]
const toArray = word => [word]
// compose :: ((b -> c), (a -> b)) -> a -> c
const compose = (f2, f1) => (...args) => f2(f1(...args))
const pipeline = compose(
toArray, // turn the string into an array
concatX // append X and turn it into a string
)
// start
pipeline(5) // ['5 X'] is the result
// So what happened here
// the input argument 5 is a value of type "a" (Number)
// we concatenated the letter X and got '5 X', a value of type "b" (String)
// we put it into an array and got ['5 X'], a value of type "c" (Array)
// concatX :: Number -> String is the morphism f :: a -> b
// toArray :: String -> [String] is the morphism g :: b -> c
// pipeline = compose(toArray, concatX) :: Number -> [String] is the composition g . f :: a -> cLet's use our imagination to understand category theory more deeply. We will draw analogies from the world around us.
We will use nature and write pseudocode that illustrates the ideas of category theory.
// Example
solid -> liquid -> gas
ice -> water -> steam
ice, water, steam // these are objects
-> // morphisms: processes applied to them (heating and so on)
turnIntoSteam . turnIntoWater :: ice -> steam // composition of processes
// A practical example
// turnIntoWater :: ice -> water
const turnIntoWater = ice => (keep at room temperature, water)
// turnIntoSteam:: water -> steam
const turnIntoSteam = water=> (apply strong heat, steam)
// composeProcesses :: ((b -> c), (a -> b)) -> a -> c
const composeProcesses = (f2, f1) => (...args) => f2(f1(...args))
const pipeline = composeProcesses(
turnIntoSteam,
turnIntoWater
)
// start
pipeline(ice) // steam is the resultKey points
- In functional programming many abstractions, laws and principles are taken from category theory.
- A category in programming is a collection of objects (data types) and morphisms between them (arrows, that is, functions).
- Morphisms f :: a -> b and g :: b -> c compose into g . f :: a -> c, read as "g after f": first f, then g.
- Composition obeys two laws: identity (f . id = f, id . f = f) and associativity (h . (g . f) = (h . g) . f).
Exercises
Exercise 1
There are three morphisms: words :: String -> [String] splits a text into words, count :: [a] -> Number returns the length of an array, and isLong :: Number -> Boolean checks that a number is greater than three. Using compose from the lesson, build the morphism isLongText :: String -> Boolean out of them. Match the functions by type: the output of each function must be accepted by the next one. Remember that compose(g, f) is "g after f".
Starter code
// compose :: ((b -> c), (a -> b)) -> a -> c
const compose = (f2, f1) => (...args) => f2(f1(...args))
// words :: String -> [String]
const words = (text) => text.split(' ')
// count :: [a] -> Number
const count = (list) => list.length
// isLong :: Number -> Boolean
const isLong = (n) => n > 3
// your code: isLongText :: String -> Boolean
console.log(isLongText('map filter reduce'))
console.log(isLongText('pipe compose curry tap lens'))Expected output
false true
Show solution
// compose :: ((b -> c), (a -> b)) -> a -> c
const compose = (f2, f1) => (...args) => f2(f1(...args))
// words :: String -> [String]
const words = (text) => text.split(' ')
// count :: [a] -> Number
const count = (list) => list.length
// isLong :: Number -> Boolean
const isLong = (n) => n > 3
// String -> [String] -> Number -> Boolean:
// first words, then count, then isLong
// isLongText :: String -> Boolean
const isLongText = compose(isLong, compose(count, words))
console.log(isLongText('map filter reduce')) // 3 words
console.log(isLongText('pipe compose curry tap lens')) // 5 wordsExercise 2
Check both category laws on the same morphisms. Write the identity morphism id :: a -> a and a function sameOn that treats two functions as equal if they give the same result on every string in the inputs list. The checks in the starter compare compose(id, countWords) and compose(countWords, id) with countWords, and then compose(isLong, compose(count, words)) with compose(compose(isLong, count), words), printing one line per check.
Starter code
// compose :: ((b -> c), (a -> b)) -> a -> c
const compose = (f2, f1) => (...args) => f2(f1(...args))
// words :: String -> [String]
const words = (text) => text.split(' ')
// count :: [a] -> Number
const count = (list) => list.length
// isLong :: Number -> Boolean
const isLong = (n) => n > 3
// the identity morphism
// id :: a -> a
// your code
// the inputs on which we compare functions
const inputs = ['map filter reduce', 'pipe compose curry tap lens', 'functor']
// two functions are equal if they give the same result on every input
// sameOn :: ((a -> b), (a -> b)) -> Boolean
// your code
// countWords :: String -> Number
const countWords = compose(count, words)
// identity: composing with id changes nothing
console.log(`id . countWords = countWords: ${sameOn(compose(id, countWords), countWords)}`)
console.log(`countWords . id = countWords: ${sameOn(compose(countWords, id), countWords)}`)
// associativity: it does not matter where the parentheses go
const left = compose(isLong, compose(count, words))
const right = compose(compose(isLong, count), words)
console.log(`isLong . (count . words) = (isLong . count) . words: ${sameOn(left, right)}`)Expected output
id . countWords = countWords: true countWords . id = countWords: true isLong . (count . words) = (isLong . count) . words: true
Show solution
// compose :: ((b -> c), (a -> b)) -> a -> c
const compose = (f2, f1) => (...args) => f2(f1(...args))
// words :: String -> [String]
const words = (text) => text.split(' ')
// count :: [a] -> Number
const count = (list) => list.length
// isLong :: Number -> Boolean
const isLong = (n) => n > 3
// the identity morphism
// id :: a -> a
const id = (x) => x
// the inputs on which we compare functions
const inputs = ['map filter reduce', 'pipe compose curry tap lens', 'functor']
// two functions are equal if they give the same result on every input
// sameOn :: ((a -> b), (a -> b)) -> Boolean
const sameOn = (f, g) => inputs.every((x) => f(x) === g(x))
// countWords :: String -> Number
const countWords = compose(count, words)
// identity: composing with id changes nothing
console.log(`id . countWords = countWords: ${sameOn(compose(id, countWords), countWords)}`)
console.log(`countWords . id = countWords: ${sameOn(compose(countWords, id), countWords)}`)
// associativity: it does not matter where the parentheses go
const left = compose(isLong, compose(count, words))
const right = compose(compose(isLong, count), words)
console.log(`isLong . (count . words) = (isLong . count) . words: ${sameOn(left, right)}`)Playground
Write and run JavaScript right here — Ramda (R) and Sanctuary (S) are available.