CoffeeScript 中的嵌套数组推导 [英] Nested array comprehensions in CoffeeScript

查看:12
本文介绍了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]

如果您使用两个数组(或字符串)调用它,则返回一个一维数组.

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

但是在 CoffeeScript 中

But in CoffeeScript

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

返回一个二维数组.

  1. 您认为这是 CoffeeScript 的设计还是错误?
  2. 如何在 CoffeScript 中展平数组?

推荐答案

首先我要说的是 2 个数组推导式并不是一个非常易于维护的模式.所以让我们把它分解一下.

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.

相反,我会自己收集结果.

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

我想这是否是 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天全站免登陆