Monads in 5 minutes
-
Upload
shay-elkin -
Category
Software
-
view
188 -
download
0
description
Transcript of Monads in 5 minutes
Monads in 5 MinutesShay Elkin
image: Rodrigo Galindez cc-by
“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
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
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
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
Moral: Monads are Easy!
Further reading:Philip Wadler,Monads for functional programming.
http://shayelk.in/5mm@srockets