A Little Bit of

Category Theory

Goes A Long Way

Mathematics

Abstractions without Leaks

Composition: Categories

The essence of a category is composition. Or, if you prefer, the essence of composition is a category.

—Bartosz Milewski

What is a Category?

Objects

Morphisms

Composition

Two Laws of a Category

1. Composition of morphisms is associative

2. An identity morphism exists for every object

Refresher: Associativity

("a" + "b") + "c"
= "a" + "b" + "c"
= "a" + ("b" + "c")

Theory Applied

Function Composition

λfλgλx.(f (g x))
var compose = function(f, g) {
    return function(x) {
        return f(g(x));
    };
};

Is this composible?

Code that composes

Compiler composition

https://github.com/CraigStuntz/TinyLanguage

module Compiler

let compile =
    Lexer.lex
    >> Parser.parse
    >> Binder.bind
    >> OptimizeBinding.optimize
    >> IlGenerator.codegen
    >> Railway.map OptimizeIl.optimize
    >> Railway.map Il.toAssemblyBuilder

Functional Programming is Math... so it must only be in its prime for stuff like financial software, right?

WRONG

Functional Programming is Math... so it must only be in its prime for stuff like financial software, right?

Algebraic Data Types

type ParseResult =
    | Success of Token * string
    | Failure of Error

Products

and

Coproducts

first : (A, B) -> A
first (a, b) = a

second : (A, B) -> B
second (a, b) = b
data AorB =
    OnlyA A
  | OnlyB B

My Journey Into FP

?

Map and endofunctors

map : Functor f => (a -> b) -> f a -> f b

safeLength : Maybe String -> Maybe Int
safeLength maybeStr = map length maybeStr

render : Signal UIState -> Signal HTML
render signal = Signal.map stateToHtml signal

Wadler and Java Generics

List v = new ArrayList();
v.add("test");
Integer i = (Integer)v.get(0);
List<String> v = new ArrayList<>();
v.add("test");
Integer i = v.get(0);

https://en.wikipedia.org/wiki/Generics_in_Java

Runtime: Boom!

Compiler: Uh, no.

Problem Solving

1. Compose atomic solutions

2. Lift the result a level of abstraction

3. Treat it as an atomic solution & repeat

0. Decompose big problems

Software Design

State -> Event -> (State, Event)
State -> Request -> (State, Response)
State -> Projection

Testing Software

Algebra

All

the

Way

Down

For Further Reference

https://bartoszmilewski.com/2014/10/28
/category-theory-for-programmers-the-preface/

Just a Little

Made with Slides.com