Geoff
Geoff

Reputation: 9590

CoffeeScript List Comprehensions / Array Comprehensions

CoffeeScript list comprehensions are slightly different from Pythons... which of these is the way that people like to return list comprehensions?

return elem+1 for elem in [1,2,3] # returns 3+1
return [elem+1 for elem in [1,2,3]].pop() # returns [2,3,4]
return (elem+1 for elem in [1,2,3]) # returns [2,3,4]

In Python, I would just write:

return [elem+1 for elem in [1,2,3]]

And it returns the list correctly, instead of a list of lists, as this would do in CoffeeScript.

Upvotes: 2

Views: 1012

Answers (2)

Trevor Burnham
Trevor Burnham

Reputation: 77416

Which of these is the way that people like to return list comprehensions?

return elem+1 for elem in [1,2,3] # returns 3+1
return [elem+1 for elem in [1,2,3]].pop() # returns [2,3,4]
return (elem+1 for elem in [1,2,3]) # returns [2,3,4]

Well, of the three options, certainly #3. But the best stylistic choice is actually this:

elem+1 for elem in [1,2,3] # returns [2,3,4]

As the last line of a function, any expression expr is equivalent to return (expr). The return keyword is very rarely necessary.

Upvotes: 9

Matti Virkkunen
Matti Virkkunen

Reputation: 65156

I've never used CoffeeScript, but if my options were getting the wrong result, doing a silly [...].pop() kludge or just using a set of parenthesis, I'd go for the parenthesis.

Upvotes: 2

Related Questions