1

in clojure I'm using the following function to initialize a 2d vector:

(defn vec2d [x y init]
  (vec (map 
         #(vec (map init (range x))) (range y))))

usage:

(def grid (vec2d 40 30 (fn [] "x")))

Since I'm new to the language, I ask myself if this is the most straight-forward way to do so. Has anyone an idea to optimize this?

Anton Harald
  • 5,772
  • 4
  • 27
  • 61

4 Answers4

3

Under the assumption that you'll always want to initialize the entries of the vector to a constant, here's how I'd do this:

(defn vec2d
  "Return an x by y vector with all entries equal to val."
  [x y val]
  (vec (repeat y (vec (repeat x val)))))
Aaron Harris
  • 876
  • 12
  • 14
2

if you want to be able to initialize according to the coordinate, you could do this

(defn vec2d [sx sy f]
  (mapv (fn[x](mapv (fn[y] (f x y)) (range sx))) (range sy)))

This allows you to have a constant value if you do

(vec2d 4 3 (constantly 2))
;; [[2 2 2 2] [2 2 2 2] [2 2 2 2]]

or initialize according to the coordinates, say:

(vec2d 4 3 (fn[x y] (+ x y))) 
(vec2d 4 3 +)                         ;; or more concisely
;;[[0 1 2 3] [1 2 3 4] [2 3 4 5]]
Shlomi
  • 4,708
  • 1
  • 23
  • 32
2

Use mapv and you're set

(defn vec2d [x y init]
  (mapv #(mapv init (range x)) (range y)))

If you want the coordinates for initialization:

(defn vec2d [x y init]
  (mapv (fn [y] (mapv #(init % y) (range x))) (range y))

A nested for it's also very readable for boards generation if you just want all cells:

(defn vec2d [cols rows init]
  (for [x (range rows) y (range cols)]
    (init x y)))

Or if you don't mind seqs:

(defn vec2d [cols rows init]
  (for [x (range rows)]
    (for [y (range cols)]
      (init x y))))
Joaquin
  • 2,714
  • 20
  • 19
0

Using a threading macro:

(defn vec-2d [r c v] (->> (repeat c v) vec (repeat r) vec))
Jeremy Caney
  • 7,102
  • 69
  • 48
  • 77
mohan
  • 31
  • 1
  • 8
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Jeremy Caney May 19 '22 at 00:13