Search code examples
clojure

Reverse a vector in clojure


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


Solution

  • 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)))))