I was searching for a Clojure logarithm function and concluded there really isn't one for v1.3+. What took me so long to invoke Math/log
was this:
user=> Math/log
CompilerException java.lang.RuntimeException: Unable to find static field: log in class java.lang.Math, compiling:(NO_SOURCE_PATH:0:0)
I tried variations like (use 'java.lang.Math)
and so forth. It wasn't until I tried an example that I found it's there after all:
user=> (Math/log 10)
2.302585092994046
This must be by design, but what is the reason?
A static method imported from Java is not a Clojure function or any other kind of Clojure object. The compiler reports any misfit as a missing field, even where the context is looking for a function. All of these ...
Math/log
(Math/log)
(map Math/log (range 1 5))
... produce such errors.
For a corresponding Clojure function:
inc
returns the function;(inc)
reports ... wrong number of args(0) ...
;(map inc (range 1 5))
returns (2 3 4 5)
.You can wrap a Java method as a Clojure one:
(defn log [x] (Math/log x))
... getting the expected result:
(map log (range 1 5))
;(0.0 0.6931471805599453 1.0986122886681098 1.3862943611198906)
The Clojure Java Interop page recommends
(map #(Math/log %) (range 1 5))
... in such cases.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With