monads in 5 minutes

17
Monads in 5 Minutes Shay Elkin

Upload: shay-elkin

Post on 22-Apr-2015

188 views

Category:

Software


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

Page 1: Monads in 5 minutes

Monads in 5 MinutesShay Elkin

Page 3: Monads in 5 minutes

“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

Page 4: Monads in 5 minutes

Caveat Emptor(Questions? — Mention @srockets)

http://shayelk.in/5mm

Page 5: Monads in 5 minutes

Functional Programming

http://shayelk.in/5mm

Page 6: Monads in 5 minutes
Page 7: Monads in 5 minutes

function foo(x) {

return y

}

function M_foo(x) {

return [y, state]

}

http://shayelk.in/5mm

Page 8: Monads in 5 minutes

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

Page 9: Monads in 5 minutes

a → Ma

http://shayelk.in/5mm

(Type constructor)

Page 10: Monads in 5 minutes

unitM(a value) → Ma

unitM(x) ~ [x, state]

http://shayelk.in/5mm

Page 11: Monads in 5 minutes

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

http://shayelk.in/5mm

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

Page 12: Monads in 5 minutes

x → (unitM∘bar) ? foo

http://shayelk.in/5mm

Page 13: Monads in 5 minutes

x → (unitM∘bar) >>= foo

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

http://shayelk.in/5mm

Page 14: Monads in 5 minutes

x → (unitM∘bar) >>= foo

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

http://shayelk.in/5mm

Page 15: Monads in 5 minutes

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

Page 16: Monads in 5 minutes

(M, unitM, bindM)and the monad rules

http://shayelk.in/5mm