Monads in 5 minutes

Post on 22-Apr-2015

183 views 0 download

description

"A monad is just a monoid in the category of endofunctors. What's the problem?" Unless you took graduate math, the problem is the above is Chinese, and most Monads introduction are no less English. At Reversim '14, I gave an ignite talk with the purpose of dispelling the audience from their fear of Monads, showing them that it could be grokked in 5 minutes, and encourage them to go read read Philip Wadler's wonderful paper. A video recording of the talk is available here: http://www.youtube.com/watch?v=-GJq0sAqOOY

Transcript of Monads in 5 minutes

Monads in 5 MinutesShay Elkin

“All told, a monad in X is just a monoid in the category of endofunctors of X, with product × replaced by composition of endofunctors and unit set by the identity endofunctor.”

Mac Lane, SaundersCategories for the Working Mathematician (2nd Ed.)

http://shayelk.in/5mm

Caveat Emptor(Questions? — Mention @srockets)

http://shayelk.in/5mm

Functional Programming

http://shayelk.in/5mm

function foo(x) {

return y

}

function M_foo(x) {

return [y, state]

}

http://shayelk.in/5mm

function foo(x) {

return y

}

function bar(x) {

return z

}

h = bar(foo(x))

function M_foo(x) {

return [y, state]

}

function M_bar(x) {

return [z, state]

}

t = M_foo(x)

if t[1] {

// handle state

} else {

t2 = M_bar(t[0])

if t2[1] // … statehttp://shayelk.in/5mm

a → Ma

http://shayelk.in/5mm

(Type constructor)

unitM(a value) → Ma

unitM(x) ~ [x, state]

http://shayelk.in/5mm

x → foo(x) → bar( foo(x) )

http://shayelk.in/5mm

(bar∘foo)(x) := bar(foo(x))

x → (unitM∘bar) ? foo

http://shayelk.in/5mm

x → (unitM∘bar) >>= foo

bindM(Ma value, Mb (*func)(a))

http://shayelk.in/5mm

x → (unitM∘bar) >>= foo

bindM(Ma value, Mb (*func)(a))

http://shayelk.in/5mm

The Maybe Monad

Ma := a | Nothing

function unitM(x) {

return { "isNothing": false, "value": x }

}

function bindM(mx, f) {

if (!mx["isNothing"]) {

return ["isNothing": false, "value": f(mx["value"])]

} else { return mx }

}

http://shayelk.in/5mm

(M, unitM, bindM)and the monad rules

http://shayelk.in/5mm