Difference in behavior of conj on vectors and list

2020-03-11 06:12发布

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

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.

1条回答
劫难
2楼-- · 2020-03-11 06:47

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.

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.

查看更多
登录 后发表回答