Suggestion: for...else (or for...empty)
ceymard opened this issue · 6 comments
Seen in other languages,
for obj in container
# do something
else
# container was empty, do something else.
or
for obj of container
# do something
empty
# container was empty, do something else.
thoughts ?
- How do you compile?
- Use cases?
Naive implementation :
for x of o
do_something x
empty
console.log "o is empty"
=>
var x, _i, _ref, _len;
for (_i = 0, _len = (_ref = o).length; _i < _len; ++_i) {
x = _ref[_i];
do_something(x);
}
if (_i == 0)
console.log("o is empty");
In the case of the in
iterator in its simplest form.
for x in o
do_something x
empty
console.log "o is empty"
var x, _seen = false;
for (x in o) {
do_something(x);
_seen = true;
}
if (!_seen)
console.log("o is empty");
Use case :
for plugin of plugins
load_plugin plugin
empty
throw new Exception "My app is useless without plugins !"
or
for plugin_name in plugins
load_plugin plugins[plugin_name]
empty
throw new Exception "My app is useless without plugins !"
Just read that on the for...else of python. Interesting read : http://psung.blogspot.com/2007/12/for-else-in-python.html
What should it return when else
clause is executed?
r =
for x of a
x
else
y
So Python's isn't like this proposal, but relative to break
. Hm.
What should it return when else clause is executed?
y
?
if the programmer wants to keep the actual for assignation logic, he should write :
r =
for x of a
x
else
[y]
So Python's isn't like this proposal, but relative to break. Hm.
Yes, wondering too which would be more worthwhile to implement.
Done mostly as proposed; both while
and for
now accept else
clause, run when the loop body wasn't run.
I don't think we should follow Python's, which is unintuitive and complicated to compile.