Hacker News new | past | comments | ask | show | jobs | submit login

First, if you can handle it, I recommend the original paper proposing monads as a solution for a wide variety of problems that every functional language has to face: http://homepages.inf.ed.ac.uk/wadler/papers/marktoberdorf/ba...

IMO, you have to understand the problems monads were meant to solve before you can understand why monads are a good solution.

Here was one key to my understanding monads. In a purely functional language you want everything to be referentially transparent. That is, an expression should be able to be substituted for its value at any given moment in time. At the very least, you'll want the ability to denote which parts of your program are referentially transparent and which aren't.

This can be expressed as utopian vision: in a purely functional language we'd like everything — everything — to be a value.

We now need some way of translating code with side effects into code that returns a value. One reasonable abstraction is to say that the "value" is not the work itself — once the work is done it's out of the bag, after all — but rather the "value" is the machine which can perform that work.

To a mathematician this screams "functor." If you want to move between the two spaces repeatedly this screams "adjoint functors." There's some work you want to do in Space A that's more easily expressed in Space B, so you take a thing in A, transform it to a thing in B, do the work in B, and then transform back to A.

Think in, e.g., Ruby: sentence.split(' ').map(&:reverse).join(' ')

split(' ') and join(' ') aren't quite inverses of each other, but they are adjoint. These pairs take us from the land of space-separated strings to the land of arrays back to the land of space separated strings.

You see that all the time in programming and mathematics. I sometimes call it the "Super Mario Brothers" maneuver when I'm trying to teach it to students. Mario wants to get to the end of the level, so he hits a block, goes up the vine to cloud land, runs through cloud land, and then comes back down.

This is a bit hand-wavey, but it's "morally correct" IMO. I mention functors because I'm hoping you've seen the maneuver I'm describing and monads are a special type of functor.




I was reading up on Monads because of the reactive course. [0] I translated the code in "Monads for functional programming" (the linked paper) to Python a few weeks back – [1]

Not sure if it will actually help anyone, but it did help me in realising that I had not understood some code, but had instead just glossed over it. The State Monad, for example. [2]

--

[0] https://www.coursera.org/course/reactive

[1] https://github.com/rm/wadler

[2] https://github.com/rm/wadler/blob/master/wadler-2.8.py




Join us for AI Startup School this June 16-17 in San Francisco!

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: