Hacker News new | ask | show | jobs
by pdpi 1452 days ago
If you want a lazy-by-default language, you need to deal with a problem — laziness means you don't need to actually evaluate the reads until you use `a` and `b`, and the print uses `b` before `a`, so the two reads can be executed in reverse order:

    a = read()
    b = read()
    print("{b}, {a}")

One of Haskell's original goals was precisely to be lazy-by-default, which necessitated coming up with a way to solve this problem, and monads are the solution they came up with that gave us reasonable ergonomics. From a practical point of view, monads are just types that have reasonable implementations for three simple functions: `pure`, `map`, and `flatten`

    # lists as monads:
    pure 1 = [1] # put a value "inside" the monad
    map f, [1, 2, 3] = [f(1), f(2), f(3)] # apply the function to the "inside" of the monad
    flatten [[1], [2, 3]] = [1,2,3]  # take two "layers" and squish them into one
    
    # also, the simplest, but least useful, way to use functions as monads:
    pure 1 = (x -> 1) # putting a value inside a function is just giving you the constant function
    map g, f = (x -> g(f(x))) # map is just composition
    flatten f = (x -> f(x)(x)) # you squish by returning a new function that performs two nested calls
("reasonable" here largely means "they follow the principle of least surprise in a formal sense")

The trick is that, once you know what monads are, you can use them in any language (with varying degrees of support), and you can see instances of them everywhere, and it's an incredibly useful abstraction. Many common patterns, (like appending to a log, reading config, managing state, error handling) can be understood as monads, and compose quite well, so your program becomes one somewhat-complex data type, a handful of somewhat-complex functions that build an abstraction around that data type, and then lots of really small, really simple functions that just touch that abstraction. I have a .class parser written in Scala that exemplifies this general structure, need to put it up somewhere public.