简体   繁体   中英

How to permanently change a vector in a clojure function with a for loop

I am trying to make make a function that will get a vector that contains letters and transform it into a vector with letter pairs

["a" "b" "c"] to ["ab" "bc"] 

I found that this function does what I need, but it seems that it doesn't change the vector that I entered as a param, instead it makes a new vector for every iteration.

(defn test [param] (for [i (range (count param))] (assoc param i 
(clojure.string/join [(get param i) (get param (inc i))]))))

Does anyone have an idea how to permanently change the elements of the vector?

clojure has a host of built-in fns to do this sort of manipulation. For example:

(->> ["a" "b" "c" "d"]                                                                                                                                                                                                                                                           
     (partition 2 1)       ; generates (("a" "b") ("b" "c") ("c" "d"))                                                                                                                                                                                                                                                        
     (map clojure.string/join)); joins the pairs
;=> ("ab" "bc" "cd")

If you really want a vector, change the map to mapv

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.

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