Gozala / hackalyst

Hack catalyst: Knowledge exchange community
9 stars 1 forks source link

Monads #7

Open Gozala opened 11 years ago

Gozala commented 11 years ago

I do believe I have an understanding of state monads & would love a session about other flavors.

Gozala commented 11 years ago

/Cc @luciferous

Raynos commented 11 years ago

The rule is your not allowed to talk about category theory when explaining monads!

Raynos commented 11 years ago

Or you have to teach everyone category theory.

luciferous commented 11 years ago

Let's look at something simple like function application. Consider the following definition of functions f and g:

// f: x -> y
var f = function(x) { return x + 1 }

// g: x -> y
var g = function(x) { return x * 3 }

Remember that every monad has two basic operators: then (composition/concatenation) and unit (think of this as instantiation, or creating a new object). There is a monad which captures the pattern of function application called the Identity monad.

 // then: Identity a -> (a -> Identity b) -> Identity b
var then = function(ma) {
    return function(q) { // q: a -> Identity b
        return q(ma);
    }
}

// unit: a -> Identity a
var unit = function(x) { return x }

Then we can compose Identitys together:

// x: Identity x
var x = unit(1);

then(x, f) // => 2
then(x, g) // => 3
then(then(x, f), g) // => 6

If unit were to box its value instead of returning it without modification, you could imagine something like the following:

x.then(f).then(g) // => 6