On May 25, 2011, at 5:30 AM, Lasse Reichstein wrote:
> On Sun, 22 May 2011 02:56:28 +0200, Brendan Eich <[email protected]> wrote:
>
>> Why is this so bad? JS programmers return, break, and continue from blocks
>> all the time.
>
> Just dawned on me that there is a significant difference.
You're right, in the case you show return from a block-lambda acts like an
uncatchable thrown exception. Some languages even model their control
statements that way.
Still, the well-behaved block-lambda use-case is block-like compared to
function expressions.
> Example (using simple block syntax)
>
> function contains(collection, y) {
> collection.forEach({|x| if (x == y) return true; });
> return false;
> }
>
> but if Collection.forEach is, e.g.,:
>
> function forEach(block) {
> for (var i = 0; i < this.length; i++) {
> try {
> block(this[i]);
> } finally {
> // Always iterate to the end!
> continue;
> }
> }
> }
>
> then what is "obviously" a "local return" in the contains function, isn't
> actually doing what
> it's expected to.
> In that sense, the block is like a function, and thinking of it as a block is
> likely to
> lead to surprises because they lack the statically detectable runtime context
> of blocks.
"likely" is not for sure. Libraries (e.g. the Array extras such as forEach) are
generally not written with finally continuing like that, even in the face of an
exception.
js> function forEach(block) {
for (var i = 0; i < this.length; i++) {
try {
block(this[i]);
} finally {
// Always iterate to the end!
continue;
}
}
}
js> a = [1,2,3]
[1, 2, 3]
js> a.forEach = forEach
function forEach(block) {for (var i = 0; i < this.length; i++) {try
{block(this[i]);} finally {continue;}}}
js> a.forEach(function (x) {print(x); throw 42})
1
2
3
This is kind of a trick function. It should be unlikely in practice, among
popular libraries.
But you're right, there are new control effects with block-lambdas not possible
with blocks, much more like functions that throw. I've been spelling out
block-lambda to avoid these being called "blocks" but I'm probably fighting a
strong tide.
If users and library authors build functional helpers well, then these "blocks"
as proposed probably will not bite back so strangely. That seems have been the
case in Smalltalk and Ruby and E.
/be_______________________________________________
es-discuss mailing list
[email protected]
https://mail.mozilla.org/listinfo/es-discuss