In case you want to get your google/wikipedia on, what Katz is talking about here is a "non-local return". Normal returns return from the immediately enclosing (i.e. local) lambda/fn/block/thing. Non-local ones unwind past multiple enclosing functions to cause an outer one to return.
In Smalltalk, the distinction is between methods and blocks. A return expression always returns from the enclosing method and will unwind past any blocks that the return expression is contained in.
In Common Lisp, I believe you name functions and then indicate the name of the enclosing function that you want to return from by doing `(return-from <fn name> 3)`.
I thought non-local returns were a bit impure and kind of a weird language novelty for a while. Recently, I added them to a hobby language of mine (Finch) and then wrote some code that uses them.
Holy crap are they awesome.
Being able to early return is, I think, one of the things that's really handy about imperative languages. I use it all the time in my code. But that cripples your ability to define your own flow-control-like structures that take functions.
For example, here's some code that sees if an array contains a given item using a for loop:
function contains(array, seek) {
for (var i = 0; i < array.length; i++) {
if (array[i] == seek) return true;
}
return false;
}
Let's say you don't like doing an explicit C-style loop and you want to make your own forEach() control-flow-like function: function forEach(array, callback) {
for (var i = 0; i < array.length; i++) {
callback(array[i]);
}
}
Now we try to refactor `contains` to use it: function contains(array, seek) {
forEach(array, function(item) {
if (item == seek) return true;
});
return false;
}
Crap, that doesn't work. There's no easy way to make `forEach()` stop early unless you go out of your way to make it support that by having the callback return some magic sentinel value. Or you do something hideous like throw a "return" exception.Non-local returns solve this neatly and end up being pretty delightful to use in practice.