Archive for October 5, 2015

Monday, October 5, 2015

What the Heck Is a Monad

Soroush Khanlou:

This is the first important part of a monad. You have to have a way to create one. In this case, the constructor, Maybe.Something, fills that role. In other languages, this is known as unit or the inconveniently-named function return. It’s a function that takes one parameter, and returns a monad that wraps that parameter.

[…]

It’s important that the block returns an already-wrapped monad, so that we can chain these calls. This is a big part of why monads are useful.

[…]

Functional programmers took a great name like ifSomething and made it totally inscrutable by calling it flatMap. (In some of the literature, it’s also known as bind. In Haskell, aka peak inscrutability, it’s invoked with the operator >>=.)

[…]

To build map, we wrap the result of the map block with the constructor and send that to flatMap:

[…]

For something to be monad, in addition to implementing bind and unit, it has to follow some special rules.

Previously: Functor and Monad in Swift, Higher Order Functions in Swift 2.

Update (2015-10-07): Jeremy W. Sherman:

Re: monads, I point people at this article when they want to tackle the hilariously compact yet accurate “monoid in the category of endofunctors” definition. Unpacks the jargon, but does use Haskell syntax.