0

In coffeescript we can do this way:

rows = [
    {a: 1}
    {b: 2}
]

for row in rows
    for k,v of row
        alert "#{k}: #{v}"

So why we can't do that this way?:

for k,v of row for row in rows
    alert "#{k}: #{v}"
0

3 Answers 3

4

You cannot do it that way, but you can invert the inner loop and put the loop construct after the expression:

for row in rows
  alert "#{k}: #{v}" for k,v of row

And, as that inner loop is also an expression, you can also invert the outer loop the same way :D

alert "#{k}: #{v}" for k,v of row for row in rows

The most similar to what you were trying to write is probably this:

for row in rows then for k,v of row 
  alert "#{k}: #{v}"

Which can be further inlined using another then (the then keyword is usually equivalent to a newline and adding one level of indentation):

for row in rows then for k,v of row then alert "#{k}: #{v}"

All of these alternatives generate the same JS code, so picking one or another will not result on degraded performance or anything like that :D

Sign up to request clarification or add additional context in comments.

Comments

0

Because that compound syntax isn't part of the Coffeescript language. Programming languages are not as fluid as human languages.

1 Comment

Question isn't about fluid as human languages. Python lambdas allow us to write more complicated expressions inline. Maybe iteration above can be written in CS but i didn't recognize how.
0

When you try to run for k,v of row for row in rows you get Parse error on line 1: Unexpected 'FOR'.

That's because the moment you put something before for row in rows, it must be an expression, and for k,v of row isn't one. You can verify this by making the prefixed loop an actual expression:

row for k,v of row for row in rows

This compiles. So, the same way you used the postfix form for iterating over rows, you have to postfix the inner one:

alert "#{k}: #{v}" for k,v of row for row in rows

To achieve the separation you want, you need to use then to replace newlines, instead of using a postfix expression:

for row in rows then for k,v of row
    alert "#{k}: #{v}"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.