22

In Python

def cross(A, B):
   "Cross product of elements in A and elements in B."
   return [a+b for a in A for b in B]

returns an one-dimensional array if you call it with two arrays (or strings).

But in CoffeeScript

cross = (A, B) -> (a+b for a in A for b in B)

returns a two-dimensional array.

  1. Do you think it's by design in CoffeeScript or is it a bug?
  2. How do I flatten arrays in CoffeScript?
1

2 Answers 2

17

First I would say say that 2 array comprehensions in line is not a very maintainable pattern. So lets break it down a little.

cross = (A, B) ->
  for a in A
    for b in B
      a+b

alert JSON.stringify(cross [1,2], [3,4])

What's happening here is that the inner creates a closure, which has its own comprehension collector. So it runs all the b's, then returns the results as an array which gets pushed onto the parent comprehension result collector. You are sort of expecting a return value from an inner loop, which is a bit funky.

Instead I would simply collect the results myself.

cross = (A, B) ->
  results = []
  for a in A
    for b in B
      results.push a + b
  results

alert JSON.stringify(cross [1,2], [3,4])

Or if you still wanted to do some crazy comprehension magic:

cross = (A, B) ->
  results = []
  results = results.concat a+b for b in B for a in A
  results

alert JSON.stringify(cross [1,2], [3,4])

Whether this is a bug in CS or not is a bit debatable, I suppose. But I would argue it's good practice to do more explicit comprehension result handling when dealing with nested iterators.

2
  • 3
    "First I would say say that 2 array comprehensions in line like is not a very maintaible pattern." - tell that to Peter Norvig :) norvig.com/sudoku.py Apr 16, 2011 at 11:54
  • Would be nice if support for flattened results was added in the syntax though. For example a comma might be introduced to the syntax - a+b for a in A,b in B
    – KalEl
    Jun 18, 2013 at 22:17
7

https://github.com/jashkenas/coffee-script/issues/1191

1
  • jashkenas reopened the issue September 13, 2011 Oct 9, 2011 at 7:09

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.