I was looking at ways to reverse a collection using Clojure without using the reverse
function and stumbled upon this solution.
(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.
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.
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]. 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.
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').
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.