do
x <- [1, 2, 3]
y <- [4, 5, 6]
return (x + y)
-- [5, 6, 7, 6, 7, 8, 7, 8, 9]
Here we have a series of assignments followed by an expression computing a result. You can't tell directly, but this is using do-notation in the List monad -- an assignment `x <- [...]` picks a value from the list, then continues. In fact, this code is run once for every possible choice from the given lists, and all of the results are aggregated into a list.The earlier commenter referred to the Identity monad, which would look like:
do
x <- 3
y <- 5
return (x + y)
-- 8
No special lists this time -- what you put on the right is what gets stored in the variable on the left. This is what you're used to in any imperative language.I suspect `bb` is a little more special, because Ron mentioned it has similarities to LOOP. I'd guess it supports recursive definitions somehow, but it's not clear what the difference actually is.
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.I guess in a OOP langague like C++ it would be something like:
foo1(); foo2(); return foo3();
?
do, afaik, just flips the written expression and use actual bind functions depending on the typeclass at point