What the heck is a Monad?

 

XKCD_Monadtrailer film John Wick: Chapter 2

Credit: xkcd

Lately, I’ve been attempting to transition more of my code from Objective-C to Swift. Consequently, I’ve also been trying to wrap my head around some of Swifts functional aspects like Functors and Monads. Knowing that functional programming can sometimes seem overtly academic and less practical, I was somewhat reluctant to begin my studies. But once I mustered the courage to begin, I found that most  documentation/posts on the topic too terse or dense for my liking- lacking on some aspects and convoluted on others. I’ve looked at great posts involving burritos and Javier’s attempt at practical pedagogy. Both do a great job at breaking things down, but I was left hungering for more. So, I’ve decided to write this post as a reference for myself and anyone else who might also feel this way.

A lot of people over-complicate the monad definition with el diablo en los detailles. Let’s avoid that, mkay? A monad is a function that takes a function as an argument and returns something. So essentially, we can think of it like a functional factory that performs some kind chaining/composition of functions and returns an expected result. Swift standard functions like map and flatmap are perfect examples of this.

Your overall takeaway should be that any type that can implement map or flatmap is a monad. If you’re one of those kooky tinfoil hat types who needs more info than this for the sake of sanity, here’s a great video detailing the messy bits: http://2014.funswiftconf.com/speakers/john.html

Please write a comment if you’d like to point out a correction of just say hi.

Leave a Reply

Your email address will not be published. Required fields are marked *