Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clojure - Applying a Function to a vector of vectors

Tags:

clojure

I have a vector [[[1 2] [3 4]] [[5 6] [7 8]] [9 10] 11]. I want to apply a function to this vector but keep the data structure.

For example I want to add 1 to every number but keep the data structure to get the result being [[[2 3] [4 5]] [[6 7] [8 9]] [10 11] 12]. Is this possible?

I have tried

(map #(+ 1 %) (flatten [[[1 2] [3 4]] [[5 6] [7 8]] [9 10] 11]))
=> (2 3 4 5 6 7 8 9 10 11 12)

But you can see that the data structure is not the same.

Is there maybe a function that takes (2 3 4 5 6 7 8 9 10 11 12) to [[[2 3] [4 5]] [[6 7] [8 9]] [10 11] 12]

I thought maybe to use postwalk but I'm not sure if this is correct.

Any help would be much appreciated

like image 645
rbb Avatar asked Jul 14 '17 09:07

rbb


2 Answers

You can use postwalk:

(require '[clojure.walk :as walk])

(let [t [[[1 2] [3 4]] [[5 6] [7 8]] [9 10] 11]]
  (walk/postwalk (fn [x] (if (number? x) (inc x) x)) t))
like image 197
Lee Avatar answered Nov 15 '22 08:11

Lee


also the classic recursive solution is not much more difficult:

(defn inc-rec [data]
  (mapv #((if (vector? %) inc-rec inc) %) data))
#'user/inc-rec

user> (inc-rec [1 [2 3 [4 5] [6 7]] [[8 9] 10]])
;;=> [2 [3 4 [5 6] [7 8]] [[9 10] 11]]
like image 4
leetwinski Avatar answered Nov 15 '22 08:11

leetwinski