conj 在 Clojure 中的向量和列表上的行为差异

编程入门 行业动态 更新时间:2024-10-25 02:18:53
本文介绍了conj 在 Clojure 中的向量和列表上的行为差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am new to clojure, initially i am going through Clojure 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屋!

更多推荐

[db:关键词]

本文发布于:2023-03-27 08:16:51,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/686592.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:向量   表上   差异   conj   Clojure

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!