Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clojure function evaluation

Tags:

java

clojure

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?

like image 592
dan Avatar asked Dec 19 '22 01:12

dan


1 Answers

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.

like image 50
Thumbnail Avatar answered Jan 01 '23 16:01

Thumbnail