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

This is exactly what the flatMap (aka monadic bind) calls do. flatMap/bind is sometimes called "a programmable semicolon", allowing one to customize what happens when chaining operations.

Can you explain the "a programmable semicolon" part? I've tried and tried and can't think of any way that makes sense to me. I use flatMap all the time but still don't understand the expression.

I understand monads and don't think it's a helpful metaphor, just kind of cute once you already understand what it's trying to explain.

At least I understand the metaphor as "being able to inject logic, depending on some context, between each operation in a sequence of operations". Alternatively, it could be thought as programmable function composition. So, for instance with the Either monad, instead of some code like

    var x = foo();
    var y = bar(x); 
    var z = baz(y);
you'd have

    var x = foo(); // returns an Either
    var y = x.flatMap(bar);
    var z = y.flatMap(baz);
where some extra computation happens in the flatMap calls that actually determines whether and/or how the function is called and what the actual return value is. In Either's case, if any of the chained operations returns an error, the subsequent operations are not executed and the error is propagated to the end of the sequence instead.

Don't think too hard. You need lots of context: Mostly that a sequence of two statements in a procedural language like C (where these are separated by semicolons) means to "execute the statements and realize their effects one after another". And then maybe you should know Monads as used in Haskell (you could say monads generalize the semicolon to include other meanings such as "can fail", "can have multiple results", "can do IO" etc).

In Haskell a semicolon can optionally be used to separate consecutive monadic binds. It basically means you can change the meaning of chaining flatMaps.

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