简体   繁体   English

Clojure的reduce函数如何工作以反转列表而不是向量

[英]How does Clojure's reduce function work to reverse a list but not a vector

I was looking at ways to reverse a collection using Clojure without using the reverse function and stumbled upon this solution. 我一直在寻找使用Clojure反转集合而不使用reverse功能的方法,偶然发现了该解决方案。

(reduce conj '() [1 2 3 4 5]) => (5 4 3 2 1) 

I have read the Clojure api with regard to how reduce works but am still baffled as to how it is working in this instance. 我已经阅读了有关Clojure api的关于reduce如何工作的信息,但是对于在这种情况下它如何工作仍然感到困惑。

Also I have found if I were to pass a vector as the third argument instead of a list ie: 我也发现是否要通过向量作为第三个参数而不是列表,即:

(reduce conj [] [1 2 3 4 5]) => [1 2 3 4 5]

I seem to get back the same vector. 我似乎找回了同样的载体。

I was wondering if anybody could give me a brief explanation as to to how reduce is working in both instances. 我想知道是否有人可以对我在这两种情况下如何reduce工作做一个简短的解释。

Also I have found this method also reverses a vector: 我也发现这种方法也可以反转向量:

(into () [1 2 3 4]) => (4 3 2 1) ; ???

The doc string says: conj[oin]. doc字符串说:conj [oin]。 Returns a new collection with the xs 'added'. 返回带有“已添加” xs的新集合。 (conj nil item) returns (item). (组合项)返回(项目)。 The 'addition' may happen at different 'places' depending on the concrete type. 取决于具体类型,“添加”可能发生在不同的“位置”。

For a vector, the natural place to add is the end. 对于矢量,添加的自然位置就是终点。 For a list, the natural place to add is the front (as with 'cons'). 对于列表,添加的自然位置是最前面(与'cons'一样)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM