user=> (Integer/rotateRight 0 0)
0
user=> (apply Integer/rotateRight [0 0])
CompilerException java.lang.RuntimeException: Unable to find static field:
rotateRight in class java.lang.Integer, compiling:(NO_SOURCE_PATH:172)
Run Code Online (Sandbox Code Playgroud)
有没有办法在Clojure中申请java函数?如果不是,我怎么能写一个支持这个的宏或函数?
Ger*_*ert 17
我能想到的最简单的事情是将它包装在一个函数中,但我不完全确定这是否是最佳/最惯用的方式:
user> (apply (fn [a b] (Integer/rotateRight a b)) [0 0])
0
Run Code Online (Sandbox Code Playgroud)
或者,略短但相当:
user> (apply #(Integer/rotateRight %1 %2) [0 0])
0
Run Code Online (Sandbox Code Playgroud)
或者,您可以为java方法调用创建一个正确的包装函数:
(defn rotate-right [a b]
(Integer/rotateRight a b))
Run Code Online (Sandbox Code Playgroud)
你会这样使用它:
user> (apply rotate-right [0 0])
0
Run Code Online (Sandbox Code Playgroud)
编辑:只是为了好玩,灵感来自iradik关于效率的评论,调用这种方法的三种不同方式之间的时间比较:
;; direct method call (x 1 million)
user> (time (dorun (repeatedly 1E6 #(Integer/rotateRight 2 3))))
"Elapsed time: 441.326 msecs"
nil
;; method call inside function (x 1 million)
user> (time (dorun (repeatedly 1E6 #((fn [a b] (Integer/rotateRight a b)) 2 3))))
"Elapsed time: 451.749 msecs"
nil
;; method call in function using apply (x 1 million)
user> (time (dorun (repeatedly 1E6 #(apply (fn [a b] (Integer/rotateRight a b)) [2 3]))))
"Elapsed time: 609.556 msecs"
nil
Run Code Online (Sandbox Code Playgroud)