Download - Monads in 5 minutes

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


Top Related