2daaa
2daaa

Reputation: 2888

How to type hint

How would I type hint this to get rid of the remaining reflection calls?

(def B 
     (amap ^"[[D" A i ^"[[D" B 
          (amap ^doubles (aget A (int i)) j ^doubles row 
             (* 2 (aget row (int j))))))

There's two reflection calls left, but I don't know how to get rid of them.

Upvotes: 7

Views: 5658

Answers (3)

Matti Pastell
Matti Pastell

Reputation: 9283

This page (in the end) provides good info about type hinting: http://clojure.org/java_interop. It recommends using e.g. (let [n (int)]) instead of ^Integer etc, which also makes the code much more readable. Note that a lot of the material on the internet seems to be for older versions of Clojure and you need less type hints in 1.2.

Upvotes: 0

Jouni K. Seppänen
Jouni K. Seppänen

Reputation: 44118

You don't show your complete code or the reflection warnings, but if they are what I think they are, you'll need to:

  1. hint A: (def ^"[[D" A ...) wherever you define it
  2. cast the return value of the innermost expression to double: (double (* 2 ...))

The process to come up with these fixes is to perform macroexpand on the macro, run that version, see what expressions are causing the reflection warnings, fix them, and hope that you can retrofit the hints into the original macro, which in this case is possible. I still recommend the more straightforward solution.

Upvotes: 3

Jouni K. Seppänen
Jouni K. Seppänen

Reputation: 44118

IMHO this is easier to do without the amap macro:

(set! *warn-on-reflection* true)
(def ^"[[D" A (into-array [(double-array [0 1 2]) (double-array [2 3 4])]))

(def ^"[[D" B (into-array (map aclone A))) ; aclone is shallow
(dotimes [i (alength B)]
  (let [^doubles row (aget B i)]
    (dotimes [j (alength row)]
      (aset row j (double (* 2 (aget row j)))))))

(doseq [row B]
  (prn (vec row)))

Upvotes: 1

Related Questions