3 ms·
Monad to the rescue Optional.of(op) .filter(v -> !v.cond) .map(v -> op2(v)) .filter(v2 -> !v2.cond) .map(/* do more stuff */) .orElseGet(
by _old_dude_ 3y ago
Monad to the rescue
Optional.of(op)
.filter(v -> !v.cond)
.map(v -> op2(v))
.filter(v2 -> !v2.cond)
.map(/* do more stuff */)
.orElseGet(() -> my_else)
- FeepingCreature 3y agoYep, in an expression language that's how you'd do it. However, we're an imperative language, and the advantage of `else` is that we can use an imperative construct, `if()`, to locate the else case in the code - so we don't need to handle it in the typesystem. That's an inversion from monadic languages, where types contain/emulate statements - in C-likes, statements contain expressions/types! So `breakelse` effectively is glue that lets us turn part of the type into a control flow, which is deliberately not represented in the typesystem. `Optional.case(:else: breakelse).X` and now in X, we're no longer dealing with an `Optional` at all. We're not "inside" the Optional as we would be with `map`; we've effectively everted the entire `Optional` using non-local flow from the `else` case.