Koenig Lear
Koenig Lear

Reputation: 2436

how to compile (e.g. fail) a clojure file

I'm new to clojure. I have defined a function in test.clj

(defn foldl [f val coll]
  (if (empty? coll) val
    (foldl f (f val (first coll)) (rest coll))))

I tried loading this file

user=> load-file "test.clj"
#object[clojure.lang.RT$3 0x16bb1d20 "clojure.lang.RT$3@16bb1d20"]
"test.clj"

It doesn't complain but when I try to use it

foldl + 0 (1 2 3)

I get

Syntax error compiling at (REPL:0:0).
Unable to resolve symbol: foldl in this context

#object[clojure.core$_PLUS_ 0x3df3a187 "clojure.core$_PLUS_@3df3a187"]
0
Execution error (ClassCastException) at user/eval2008 (REPL:1).
java.lang.Long cannot be cast to clojure.lang.IFn

How do I force it to compile and tell me what's wrong with the function when I load it rather than when I execute it? Also what does the error mean?

Upvotes: 1

Views: 116

Answers (1)

Lee
Lee

Reputation: 144206

You need to use parenthesis when calling functions like load-file i.e.

(load-file "test.clj")

without parenthesis this just evalutes the symbol load-file which resolves to the function and the string "test.clj". Both of these are displayed in the REPL.

Similarly when calling foldl:

(foldl + 0 '(1 2 3))

in contrast

foldl + 0 (1 2 3)

is a list of 4 forms - the symbols foldl and +, the long 0 and the list (1 2 3). Since you failed to load the file in the previous step, foldl cannot be found hence the error. + resolves to the clojure.core/+ function which is displayed in the REPL. 0 evaluates to itself and is displayed in the REPL, while the list (1 2 3) is evaulated by attempting to call 1 as a function with arguments 2 and 3. Since 1 does not implement IFn you receive the error "java.lang.Long cannot be cast to clojure.lang.IFn".

Upvotes: 1

Related Questions