How to type hint

牧云@^-^@ 提交于 2019-12-21 12:17:24

问题


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.


回答1:


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.




回答2:


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)))



回答3:


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.



来源:https://stackoverflow.com/questions/3779876/how-to-type-hint

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!