Inconsistency with Clojure's sequences?

本小妞迷上赌 提交于 2019-11-29 13:20:26

Documentation for conj (from clojure.org):

conj[oin]. Returns a new collection with the xs 'added'. (conj nil item) returns (item). The 'addition' may happen at different 'places' depending on the concrete type.

It's more efficient to "add" elements to the end of a vector, while it's more efficient to do so at the beginning of lists. conj uses whatever is the most efficient for the data structure you give it.

In the examples you give, '(1 2 3) and (seq [1 2 3]) both implement ISeq (see documentation for seq?), while [1 2 3] doesn't.

Clojure's conj ultimately calls the cons method (not to be confused with the cons function - this method is internal clojure code) on the underlying data structure; for vectors (PersistentVector), cons adds elements to the end, while for lists they're added to the front (the cons method for PersistentLists returns a new list with the new element as its head, and the existing list as its tail).

If you look at Clojure Data Structures

you'll see that conj works differently with lists and vectors.

conj puts the added item at the front of the list and at the end of a vector.

I also suggest looking at Clojure API conj

which has some nice examples. ClojureDocs overall has some very nice examples for most Clojure commands.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!