开发者

CoffeeScript List Comprehensions / Array Comprehensions

开发者 https://www.devze.com 2023-02-28 16:30 出处:网络
CoffeeScript list comprehensions are slightly different from Pythons... which of these is the way that people like to return list 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() #开发者_如何学Python 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.


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消