在Clojure中,向量和列表上的conj行为的差异 [英] Difference in behavior of conj on vectors and lists in Clojure

查看:95
本文介绍了在Clojure中,向量和列表上的conj行为的差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是clojure的新手,最初我通过 Clojure.org cheatbook

I am new to clojure, initially i am going through Clojure.org and cheatbook .

我想知道 conj 列表和向量。

(conj [1 2 3] 4)
[1 2 3 4]

(conj (list 3 2 1) 4) 
(4 3 2 1)


推荐答案

b $ b

当我使用它与列表它添加元素在第一个位置和向量它添加在最后一个位置。

conj 程序在不同的地方取决于具体类型。特别地, conj 是在给定数据结构的最有效的地方添加新元素。

The conj procedure adds new elements "at different 'places' depending on the concrete type". In particular, conj is adding new elements at the most efficient place for the given data structure.

- 连接列表中,插入一个新元素的最便宜的地方是头部 - 没有必要遍历列表找到插入点,只需将新元素与列表的第一个元素连接。

In a single-linked list, the cheapest place to insert a new element is at the head - there's no need to traverse the list to find the insertion point, just connect the new element with the list's first element.

在向量中,最便宜的地方是在结束 - 没有必要移动或移动其余的元素为新元素腾出空间,如果向量是用额外的可用空间与实际大小大于其当前长度(如瞬态向量和 conj!的情况,但不是持久向量),这是一个简单的问题,在第一个自由位置并将其长度增加一个单位。

In a vector, the cheapest place is at the end - there's no need to shift or move the rest of the elements to make room for the new element, and if the vector was created with extra free space with actual size greater than its current length (as is the case with transient vectors and conj!, but not with persistent vectors), it's a simple matter of adding the new element at the first free position and incrementing its length by one unit.

这篇关于在Clojure中,向量和列表上的conj行为的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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