[英]Cons (:) in CoffeeScript?
Haskell provides the :
function to prepend an item to a list: Haskell提供了
:
函数以将项目添加到列表的前面:
*Main> :t (:)
(:) :: a -> [a] -> [a]
Example: 例:
*Main> 1 : 2 : 3 : []
[1,2,3]
Does such a function/operator exist for CoffeeScript? CoffeeScript是否存在这样的功能/运算符?
As far as I can tell, CoffeeScript does not implement Haskell-like lists. 据我所知,CoffeeScript没有实现类似Haskell的列表。 The closest method/function is the Array unshift method
最接近的方法/函数是数组取消移位方法
However, the Haskell cons function creates a new list while preserving the original list, whereas Array.unshift
modifies an existing array, so they really aren't the same thing. 但是,Haskell cons函数会在保留原始列表的同时创建一个新列表,而
Array.unshift
会修改现有数组,因此它们实际上不是一回事。
There are a number implementations of linked-lists in CoffeeScript, eg: CoffeeScript中有许多链表的实现,例如:
but I don't see anything natively supported by CoffeeScript. 但我看不到CoffeeScript本身支持的任何内容。
I'd second the native unshift
method – although it will return the length of the resulting array, not the array itself , so you can't chain calls, like your example suggests. 我将使用本机
unshift
方法,尽管它会返回结果数组的长度, 而不是数组本身的长度,所以您不能像示例所示那样链接调用。
As a fun alternative, CoffeeScript's ranges feature allows splicing , which could be used to prepend a value to an existing array: 作为一种有趣的选择, CoffeeScript的ranges功能允许进行splicing ,可以将其值添加到现有数组的前面:
array = [ 1, 2, 3 ]
array[..0] = [ 4, array[0] ]
console.log array # [ 4, 1, 2, 3 ]
More precisely, it removes the first element of the array and adds the two elements on the right-hand side of the assignment (your desired prependand and the original 0-value). 更精确地讲,它删除数组的第一个元素,并在赋值的右侧添加两个元素(您所需的前缀和原始0值)。
We can even chain it, by wrapping it in parentheses and bringing in the array's referencing variable: 我们甚至可以通过将其包装在括号中并引入数组的引用变量来链接它:
array = [ 1, 2, 3 ]
(( array[..0] = [ 4, array[0] ] ) and array).unshift(5)
console.log array # [ 5, 4, 1, 2, 3 ]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.