←back to thread

A list is a monad

(alexyorke.github.io)
153 points polygot | 2 comments | | HN request time: 0.636s | source
Show context
kerblang ◴[] No.44447914[source]
The way I think of it, monads are a solution to Callback Hell, where you've fallen in love with lambdas, but now you have a nightmarish mess of lambdas in lambdas and lambdas calling lambdas. The monadic functions allow you to create "for comprehensions" aka "do comprehensions" but really, they look like a classic for-each loop. They secretly call the monadic map/flatMap/filter functions.

    for x in list
        doThings(x)
These comprehensions have a strange bonus feature, that you can do nested "loops" all at once, and even add "guards" (little if statements)

    newlist=
        for x in list1
            y in list2 if y > 3
            z in list3
            doThings(x, y, z)
But again, the comprehension, when "de-sugared", is secretly calling the map/flatMap/filter functions of list1, list2, list3 to get our result. You as the author of a given monad can implement those functions however you want, and they're all 3 lambda based. But notice how the comprehension is flattening those lambdas out! Our callbacks in callbacks are much more readable like this.

Without comprehensions, you can still implement monadic functions in any old language (probably in C...?), and they're handy in their own right, but you don't get the flattening-of-callback-hell magic.

replies(1): >>44447956 #
stronglikedan ◴[] No.44447956[source]
After reading your comment, I've made it my mission to understand it. Although I have no idea what you're talking about, you make it sound intriguing.
replies(6): >>44448147 #>>44448192 #>>44448734 #>>44449291 #>>44450891 #>>44452126 #
1. kerblang ◴[] No.44448192[source]
First off, I'm not sure it's even worth it to understand this stuff... Second, someone should be along to slam it soon enough and insist I've missed some gibberishy business that you'll never understand.

With those caveats in mind, here's a more intensive scala-based monad tutorial I made:

https://github.com/zaboople/techknow/blob/master/scala/monad...

But really, don't burn up too much of your short life trying to come to terms with this stuff. There's a reason most languages don't get around to supporting Monads...

replies(1): >>44448325 #
2. nine_k ◴[] No.44448325[source]
It' really worth understanding. I studies Haskell and Scala to write better Python, Typescript, and Java, and it did help.

The whole thing about JS's Promises becomes way clearer when you see that they are a monad, except for one discrepancy (they auto-flatten themselves). It leads to much shorter and clearer code when doing pedestrian frontend stuff.