Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP

Loading…

Suggestion: for...else (or for...empty) #75

Closed
ceymard opened this Issue · 6 comments

2 participants

@ceymard

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 ?

@satyr
Owner
  • How do you compile?
  • Use cases?
@ceymard

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 !"
@ceymard

Just read that on the for...else of python. Interesting read : http://psung.blogspot.com/2007/12/for-else-in-python.html

@satyr
Owner

What should it return when else clause is executed?

r =
  for x of a
    x
  else
    y

http://psung.blogspot.com/2007/12/for-else-in-python.html

So Python's isn't like this proposal, but relative to break. Hm.

@ceymard

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.

@satyr satyr closed this in 62c59a7
@satyr
Owner

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.