←back to thread

A list is a monad

(alexyorke.github.io)
153 points polygot | 1 comments | | HN request time: 0.205s | 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. anchpop ◴[] No.44449291[source]
I wrote a post about a highly related topic here. It may be helpful to you in understanding the parent comment: https://chadnauseam.com/coding/random/how-side-effects-work-...