CoffeeScript中的嵌套数组结果 [英] Nested array comprehensions in CoffeeScript

查看:183
本文介绍了CoffeeScript中的嵌套数组结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在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]

返回一个

但在CoffeeScript中

But in CoffeeScript

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

返回一个二维数组。 / p>

returns a two-dimensional array.


  1. 您认为这是CoffeeScript的设计还是错误?

  2. CoffeScript中的数组?


推荐答案

一个非常可维护的模式。

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])

这里发生的是内部创建一个闭包,它有自己的理解收集器。所以它运行所有的b,然后返回结果作为数组,推送到父结果收集器。

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.

而是我自己收集结果。

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])

这是否是CS中的错误是有点有争议,我想。但我认为,在处理嵌套迭代器时执行更明确的解析结果处理是一个好习惯。

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.

这篇关于CoffeeScript中的嵌套数组结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆