Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CoffeeScript List Comprehensions / Array Comprehensions

Tags:

coffeescript

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.

like image 390
Geoff Avatar asked Feb 16 '26 11:02

Geoff


2 Answers

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.

like image 71
Trevor Burnham Avatar answered Feb 19 '26 13:02

Trevor Burnham


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.

like image 43
Matti Virkkunen Avatar answered Feb 19 '26 13:02

Matti Virkkunen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!