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

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

问题描述

我是 clojure 的新手,最初我正在浏览 Clojure.org作弊本 .

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

我想知道 conj 在列表和向量上的不同行为的确切原因是什么.

I want to know what is exact reason for different behavior of conj on list and vector.

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

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

当我将它与列表一起使用时,它会在第一个位置添加元素,并在最后一个位置添加向量.

when i am using it with list it add element in first location and with vector it add at last location.

推荐答案

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.

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

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