tags:

views:

145

answers:

2

A Java API I am Clojure interoping with requires that I pass it a 2d array of doubles; double[][]. How do I create a primitive 2d array of doubles in Clojure? I am looking for something like this

(double-array-2d [[1 2] [3 4]])

This function would have a Java return type of double[][].

+2  A: 

Try this:

(defn double-array-2d [coll]
  (let [w (count coll)
        h (apply max (map count coll))
        arr (make-array Double/TYPE w h)]
    (doseq [x (range w)
            y (range h)]
      (aset arr x y (double (get-in coll [x y]))))
    arr))
Brian Carper
Thanks @Brian. I like your blog, BTW.
Julien Chastang
+7  A: 

Try this:

(into-array (map double-array [[1 2] [3 4]]))
fogus
Thanks @fogus. That is a nice, elegant solution. I look forward to the completion of your book.
Julien Chastang
Is this the fastest way possible? Does this already take care of type hinting?
Hamish Grubijan