简体   繁体   English

Swift中的“ cons”运算符/函数/方法在哪里?

[英]Where is the “cons” operator / function / method in Swift?

Many functional languages have a cons operator . 许多功能语言都有一个cons运算符 It returns the result of an immutable list or array like type, with a new element attached to the end, in constant time. 它以固定时间返回不可变列表或类似数组类型的结果,并在末尾附加了新元素。

As a pseudo code example, [1,2] : 3 would evaluate to [1,2,3] . 作为伪代码示例, [1,2] : 3计算结果为[1,2,3]

Swift has append to add an element to an Array in amortised constant time (with some caveats). Swift已append了在摊销后的固定时间内将元素添加到Array (有一些注意事项)。 However, append requires a mutable Array . 但是, append需要一个可变的Array I can create a mutable Array from an immutable one and then append , but I am very surprised that there does not seem to be an existing function or operator that does this for me and provides the amortised constant time guarantee (where not shared). 我可以从一个不可变的Array创建一个可变Array ,然后append ,但令我感到惊讶的是,似乎没有现成的函数或运算符可以为我执行此操作并提供摊销的固定时间保证(不共享)。

This is not the cons operator, per se, but you can use the + operator for arrays to append or prepend an array onto a mutable or immutable array in "constructor style"; 本质上,这不是cons运算符,但是您可以对数组使用+运算符,以“构造函数样式”将数组追加或添加到可变或不可变数组上; constructing a new array with the concatenated result. 用连接的结果构造一个新的数组。

From the Swift Language Guide - Collection Types : 来自Swift语言指南-集合类型

Creating an Array by Adding Two Arrays Together 通过将两个数组加在一起来创建数组

You can create a new array by adding together two existing arrays with compatible types with the addition operator ( + ). 您可以通过使用加法运算符( + )将两个具有兼容类型的现有数组加在一起来创建新数组。 The new array's type is inferred from the type of the two arrays you add together: 新数组的类型是从您添加在一起的两个数组的类型推断出来的:

... ...

Ie, 也就是说,

let foo = [1, 2]
let bar = foo + [3]    // [1, 2, 3], "cons(foo, 3)"
let baz = [-1, 0] + bar // [-1, 0, 1, 2, 3], "cons([-1, 0], bar)"

Note, however, that this does not run in amortised constant time, since we require allocating new memory and copying the result into this. 但是请注意,由于我们需要分配新的内存并将结果复制到其中,因此这不会按固定的固定时间运行。 However, since arrays are value types in Swift, I don't see how how any operation on immutable arrays---such that we create a new immutable array---will run in constant time, since we will always require copying for this (even if, sometimes, this might be performed lazily). 但是,由于数组是Swift中的值类型,因此我看不到对不可变数组进行任何操作(例如我们创建一个新的不可变数组)如何在恒定时间内运行,因为我们始终需要为此进行复制(即使有时可能会延迟执行)。

Hence, the performance of the above shouldn't differ from constructing a new array using .append / .appendContentsOf on an existing mutable one followed by copying ; 因此,上述性能应与在现有可变.appendContentsOf上使用.append / .appendContentsOf构造数组, 然后进行复制 the former step running in amortised constant time (due to exponentially growing pre-allocation of array space), but the latter one running in linear time. 前一步以摊销的恒定时间运行(由于数组空间的预分配呈指数增长),而后者以线性时间运行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM