English 中文(简体)
在列表理解中共同描述assoc数组语法
原标题:Coffeescript assoc array syntax in a list comprehension

大家好:我经常遇到以下关于咖啡脚本的问题,想知道是否有人知道解决方案。请考虑以下代码:

k=for x in [0...3]
   {foo:{bar:x,baz:3},qux:5}

我有很多代码都有这种基本布局。然而,它很难阅读。以以下方式编写此代码会更干净:

#Gives Error- PARSE ERROR ON LINE 5: UNEXPECTED  TERMINATOR 
k=for x in [0...3]
   foo:
      bar:x
      baz:3
   qux:5

这个错误可以通过下面的破解来规避,看起来真的很难看:

k=for x in [0...3]
   g=
      foo:
         bar:x
         baz:3
      qux:5
   g

有人知道在理解中使用Coffeescapet的多行assoc数组语法而不会遇到这个错误的干净方法吗?谢谢你的帮助!

最佳回答

所以

k=for x in [0...3]
   foo:
      bar:x
      baz:3
   qux:5

未能编译,但是

func
   foo:
      bar:x
      baz:3
   qux:5

(例如)编译正确。我相信这是CoffeeScript解析器中的一个已知错误。不幸的是,还有几个类似的问题悬而未决,因为解析YAML样式的对象变得异常棘手。所以现在,我会使用显式花括号,就像c3rin建议的那样。

[编辑:请参阅特别发布981。]

问题回答

.map()是您的好友:

k = [0...3].map (i) ->
    foo:
        bar: "#{i}"
        baz: i
    qux: i*3

(我知道你的问题实际上是一个bug,但这更有意义。列表理解更适合简单的任务)

我已经更改了几次答案,但我认为第一个例子的问题是,coffeescript编译器认为foo:是你想要构建的对象,并且在它到达qux时很担心:因为它认为它与foo完全不同。有趣的是,您可以混合JSON样式和YAML样式的声明,使用JSON样式的大括号显式地声明对象定义的边界,并在边界内部使用YAML以提高可读性。

{
  foo:
    bar:x
    baz:3
  qux:5
}

我通常的解决方案如下:

k = for x in [0...3]
   g =
      foo:
         bar:x
         baz:3
      qux:5

设置变量会返回其设置的值。这仍然有点麻烦,但比设置后显式返回g的版本稍微好一点。不过,这绝对是解决coffeescript错误的方法。





相关问题
Why is list comprehension called so in Python?

I know Python is not the first language to have list comprehension. I m just interested in the history of the name. I m particularly interested in why it s called comprehension Why is list ...

implementing a per-digit counter using the list monad

So, I was looking at the question here, and built a rather ugly solution for the problem. While trying to clean it up, I started investigating list comprehensions and the list monad. What I decided ...

Pythonic List Comprehension

This seems like a common task, alter some elements of an array, but my solution didn t feel very pythonic. Is there a better way to build urls with list comprehension? links = re.findall(r"(?:https?:/...

List comprehension won t give correct result in Haskell

I am doing project euler question 136, and came up with the following to test the example given: module Main where import Data.List unsum x y z n = (y > 0) && (z > 0) && (((x*x)...

Running average in Python

Is there a pythonic way to build up a list that contains a running average of some function? After reading a fun little piece about Martians, black boxes, and the Cauchy distribution, I thought it ...

Most useful list-comprehension construction?

What Python s user-made list-comprehension construction is the most useful? I have created the following two quantifiers, which I use to do different verification operations: def every(f, L): ...

Create a dictionary with comprehension

Can I use list comprehension syntax to create a dictionary? For example, by iterating over pairs of keys and values: d = {... for k, v in zip(keys, values)}

热门标签