I do have a question regarding early returning the outer function scope, what happens if in your forEach definition, you actually do work on some (or all) elements that needs to be undone. If the outer forEach function is returned early by the anonymous function, how will any of the clean up code get called?
// returns true/false
array.some(function(item){
item === seek
})
Your "magic sentinel value" would be a Boolean, which is exactly how `some` is implemented: function forEach(array, callback) {
for (var i = 0; i < array.length; i++) {
if (callback(array[i]) === true) break;
}
}No problemo in Ruby:
def map_unless_nested(arr)
arr.map {|v| return [] if v.is_a? Array; yield v}
end
map_unless_nested([2,3,4,5]) {|v| v+1 }
# => [3,4,5,6]
map_unless_nested([2,[3,4],5]) {|v| v+1 }
# => []
This starts looking ugly in JavaScript if we want to generalize "map". Either we can keep "map" clean and wrap our callback so it throws exceptions on array input: function map(arr, callback) {
var ret = [];
for (var i = 0; i < arr.length; i++) {
ret.push(callback(arr[i]));
}
return ret;
}
function map_unless_nested(arr, callback) {
try {
return map(arr, function(v) {
if (v instanceof Array) throw "nested!";
return callback(v);
});
} catch (e) {
if (e==="nested!") { return []; }
throw e;
}
}
map_unless_nested([2,3,4,5], function(v){ return v + 1; })
// => [3,4,5,6]
map_unless_nested([2,[3,4],5], function(v){ return v + 1; })
// => []
Or, if we want to keep the callback clean, we have to start fiddling with map, and then it's no longer really just map (it's map with halting parameters), and then you're using special return values to inform calling functions that the halting condition was met. function map_unless_test(arr, callback, test) {
var ret = [];
for (var i = 0; i < arr.length; i++) {
if (test(arr[i])) { return false; }
ret.push(callback(arr[i]));
}
return ret;
}
function map_unless_nested(arr, callback) {
return map_unless_test(arr, callback, function(v) {
return v instanceof Array;
}) || [];
}
If you still think that exceptions are the best language feature to solve this example, consider the situation where you want to do something with those nested arrays. For example, let's take the Ruby example and modify it so it will return a copy of the first-encountered innermost array with the callback applied. def map_first_innermost(arr, &block)
arr.map do |v|
return map_first_innermost(v, &block) if v.is_a? Array
yield v
end
end
That was easy. You can see that non-local returns become useful very quickly. function map_unless_nested(arr){
return arr.filter(function(it){ if (it instanceof Array) return it }).length?
function(){ return [] } : function(fn){ return arr.map(fn) };
}
console.log(map_unless_nested([1,2,3])(function(n){ return n + 1 }));
console.log(map_unless_nested([1,2,[1,2],3])(function(n){ return n + 1 }));
edit: also a translation for the last example function map_first_innermost(arr){
return function(fn){
return arr.map(function(v){
if (v instanceof Array)
return map_first_innermost(v)(fn);
return fn(v);
});
};
}
console.log(map_first_innermost([1,2,[1,2],3])(function(n){ return n + 1 })); function map_unless_nested(arr, cb){
var res = []
var has_nested = arr.some(function(item){
if (item instanceof Array) return true
res.push(cb(item))
})
return has_nested ? [] : res
}
function map_first_innermost(arr, cb){
var res = []
var has_nested = arr.some(function(item){
if (item instanceof Array) return true
res.push(cb(item))
})
return has_nested
? map_first_innermost(res[res.length-1], cb)
: res
}That's not an outlandish requirement; imagine that the callback can be expensive, and we would like to be able to adjust a centralized "map" function later so it farms things out to different processes/workers/etc.
To solve this for map_first_innermost, you'd have to throw an exception with the nested array, but this is just getting hideously ugly.
function map_first_innermost(arr, callback) {
try {
return map(arr, function(v) {
if (v instanceof Array) throw {itWasNested: v};
return callback(v);
});
} catch (e) {
if (e.itWasNested) {
return map_first_innermost(e.itWasNested, callback);
}
throw e;
}
}It sounds like you think my requirements are contrived. If you prefer to use functions as iterators in JavaScript, and who doesn't (unless you like polluting methods with counter variables?) ... there is no way to have iterators halt early without throwing exceptions or coming up with special return values. Every programmer needs to iterate and break out of loops. It is easy to break from iterator functions in Python and Ruby, since the languages natively support this concept. JavaScript doesn't--that's all we're saying, and it would be nice.
The GP is creating a (toy) language and observes that non-local returns make some code easier/cleaner to write and that non-local returns are therefore not just a language wart, but something to carefully consider when designing a programming language.
function callcc(f){
f(function(x){ return x })
}Exactly right. That's the one nasty corner case I know of. I don't know how often it comes up in practice. I believe Ruby handles it by trying to make blocks not-very-first-class so that it's hard to capture one and have its extent outlast the outer stack frames.
class BlockInvoker
def initialize(&block)
@block = block
end
def invoke
@block.call
end
end
BlockInvoker.new { puts 1 }.invoke
def get_block_invoker
BlockInvoker.new { return }
end
get_block_invoker.invoke
I tried to cover this a bit in my post. For callbacks, this semantic is clunkier.function getMyData(input) { asyncDataCall(input, {|data| return data; // fail }); }
And not surprisingly some mad nutter has already implemented it in Perl - https://metacpan.org/module/Scope::Escape::Sugar
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:
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: Now we try to refactor `contains` to use it: 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.