The correct form for using a 2D array in Clojure and initializing each cell

(Lisp beginner) I need to create a 2D array and initialize each cell in the array. Each cell is initialized with a function that is based on the data in the previous cell. Thus, a cell like 0.1 will be initialized with the result of a function that uses the data from cell 0.0, etc.

I was wondering what the correct clojure idiom is for setting up such a data structure.

+5
source share
2 answers

The representation of your array actually depends on the need to use it, and not to initialize it. For example, if you have a dense matrix, you most likely should use a vector of vectors, for example:

[[0, 1, 2, 3, 4],
 [5, 6, 7, 8, 9],
 [9, 8, 7, 6, 5],
 [4, 3, 2, 1, 0],
 [0, 1, 2, 3, 4]]

:

{:length 5
 :data
 [0, 1, 2, 3, 4, 
 5, 6, 7, 8, 9,
 9, 8, 7, 6, 5, 
 4, 3, 2, 1, 0, 
 0, 1, 2, 3, 4]
}

, hash-map s:

{0 {0 0, 4 4},
 2 {2 7},
 3 {0 4, 2 2}}

( 2D- , , , ).

(, ..), , Incanter.

, transients , ( ):

(defn make-array [initial-value f length]
  (loop [result (transient []), length-left length, interim-value initial-value]
    (if (= length-left 0)
        (persistent! result)
        (recur (conj! result (f interim-value)) (- length-left 1) (f interim-value))))

, .

+10

, , ( ) , 2D "". :

{ [x y] value ... }

, - . , , , ffriend.

+2

All Articles