Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Multiple generators in list comprehensions #2640

Closed
gampleman opened this issue Dec 9, 2012 · 5 comments
Closed

Multiple generators in list comprehensions #2640

gampleman opened this issue Dec 9, 2012 · 5 comments

Comments

@gampleman
Copy link

I was writing a Haskell tutorial for my students today. They were to write a function that returns all the possible sums of two lists:

sums as bs = [a + b | a <- as, b <- bs]

So I thought: let's try that in coffee:

sums = (as, bs) -> a + b for a in as for b in bs

which produces this beast of js:

var sums;

sums = function(as, bs) {
  var a, b, _i, _len, _results;
  _results = [];
  for (_i = 0, _len = bs.length; _i < _len; _i++) {
    b = bs[_i];
    _results.push((function() {
      var _j, _len1, _results1;
      _results1 = [];
      for (_j = 0, _len1 = as.length; _j < _len1; _j++) {
        a = as[_j];
        _results1.push(a + b);
      }
      return _results1;
    })());
  }
  return _results;
};

As you can see this will produce an array of arrays rather then a single array. Another problem comes when you wish to use guards:

sums = (as, bs) -> a + b for a in as for b in bs when a > b

This will not work, as a is not in scope yet.


My proposal is to change the semantics to allow guard expressions at the end of the list comprehension to be evaluated in the inmost loop.

Also the loop should be compiled rather to this:

var sums;

sums = function(as, bs) {
  var a, b, _i, _len, _results;
  _results = [];
  for (_i = 0, _len = bs.length; _i < _len; _i++) {
    b = bs[_i];
    var _j, _len1;
    for (_j = 0, _len1 = as.length; _j < _len1; _j++) {
      a = as[_j];
      _results.push(a + b);
    }
  }
  return _results;
};
@vendethiel
Copy link
Collaborator

Discussed multiple times already #2030
Also see http://brehaut.net/blog/2011/coffeescript_comprehensions

@gampleman
Copy link
Author

Ah the language I used was a bit different, so I couldn't find it. Thanks. Closing for now.

@vendethiel
Copy link
Collaborator

That's my job ;)

@michaelficarra
Copy link
Collaborator

FWIW, I'd prefer to switch to the proposed semantics.

@jashkenas
Copy link
Owner

Yes -- I think it's worth talking about (over in #2030), especially if we can have our cake and eat it too -- have a way of allowing the inner comprehension to either be treated as an expression, or flattened out.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

4 participants