4 ms·
Good question. "Do notation" is sometimes referred to as "the programmable semicolon", because how you go from one statement to the next depends on which monad
by Twisol 4y ago
Good question. "Do notation" is sometimes referred to as "the programmable semicolon", because how you go from one statement to the next depends on which monad you're in. (In the List example, the assignment `x <- [1, 2, 3]` forked execution three ways before proceeding to the next assignment.)
In Java, the semicolon is pretty much fixed; you can't change the relationship between statements in any meaningful way. So you have to play tricks. You can implement the List example in a crafty but leaky way:
do(() -> {
var x = choose(1, 2, 3);
var y = choose(4, 5, 6);
return x + y;
});
When `choose` is called for the first time, it remembers which choice it returns to you. When you `return` from the block, your result is stored, and then the function is re-executed -- except this time, `choose` will now return a different value (the next one). You can implement this in a rather small handful of lines, but it's very tight and clever code, and not at all obvious how it works at first glance.
There's another way to do this, with chained `flatMap` calls, like:
list(1, 2, 3).flatMap(x ->
list(4, 5, 6).flatMap(y ->
list(x + y)));
...but that's so different from "normal" use of a language like Java that readers and writers alike are likely to balk to some extent.