6

Hi I just starting with Clojure and I cannot manage to reverse a vector of integers.

;generate a vector of random integers
(defn generate-rands
  [x]
  (vector (take x (repeatedly #(rand-int 100))))
  )

;vector of integers
(def my-vector (generate-rands 10))

;reverse the vector of integers
(def my-vector-reversed (reverse my-vector))

;main
(defn main-app
  []  
  (println "My Vector: \t\t\t" my-vector)
  (println "My Vector Reversed: \t" my-vector-reversed))

The output is

=> (main-app)
My Vector:           [(14 49 29 3 66 7 60 60 34 19)]
My Vector Reversed:  [((14 49 29 3 66 7 60 60 34 19))]
nil
#'startingclojure.app/main-app

=> (vector? my-vector-reversed)
false

Can someone kindly explain me why my-vector-reversed is not a vector? And how can I reverse the content of 'my-vector'? Thanks

3 Answers 3

9

Also, it's preferable to use rseq instead of reverse when you work with vector or sorted-map. It has constant time, because they are indexed and can be efficiently walked in either direction.

Sign up to request clarification or add additional context in comments.

Comments

6

from reverse's doc:

Returns a seq of the items in coll in reverse order. Not lazy.

reverse turns anything into a seq, meaning, a list. in order to get back a vector you should turn it into a vector:

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

In your case, look at your "my-vector": [(14 49 29 3 66 7 60 60 34 19)] - its a vector containing a single element - a seq. so reversing it wouldnt change anything. you should use the same technique to turn your seq into a vector:

(defn generate-rands
  [x]
  (into [] (take x (repeatedly #(rand-int 100)))))

Comments

0

reverse function returns always a seq, not a vector. You can again convert the result into a vector with something like: (apply vector (reverse [1 2 3]))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.