On Feb 12, 2009, at 4:21 AM, Albert Cardona wrote:

I may be missing something fundamental about "binding", because I can't
understand how the imports fail inside the binding block:

[this works]

But this doesn't (restarted the Repl to remove imports):

user=> (import '(java.io StringWriter))
nil
user=> (def bout (StringWriter.))
#'user/bout
user=> (binding [*out* bout] (import '(java.io File)) (println (File.
"/home/albert")))
java.lang.IllegalArgumentException: Unable to resolve classname: File
(NO_SOURCE_FILE:3)
user=>

An important thing to remember is that Clojure has no interpreter. To evaluate a data structure, Clojure compiles it and then runs the compiled code. Any statements that change what the compiler knows about (like import) need to complete before the compiler is able to compile code that uses them. In your first example, that was the case. In your second example, it wasn't.

You can see this more easily with macroexpand:

user=> (macroexpand '(binding [*out* bout] (import '(java.io File)) (println (File. "/home/albert")))) (do (. clojure.lang.Var (clojure.core/pushThreadBindings (clojure.core/ hash-map (var *out*) bout))) (try (import (quote (java.io File))) (println (File. "/home/albert")) (finally (. clojure.lang.Var (clojure.core/popThreadBindings)))))
user=>

The import form had been compiled, but not yet executed when the compiler was asked to compile (File. ...).

But this works (via load-file; also restarted the Repl to remove imports):

file /home/albert/test.clj contains:
/-----8<----/
(import '(java.io File))
(println (File. "/home/albert"))
/----->8----/

user=> (import '(java.io StringWriter))
nil
user=> (def bout (StringWriter.))
#'user/bout
user=> (binding [*out* bout] (load-file "/home/albert/test.clj"))
java.lang.Exception: Unmatched delimiter: ) (test.clj:1)
user=> (binding [*out* bout] (load-file "/home/albert/test.clj"))
nil
user=> bout
/home/albert

It wasn't about the binding. When the file was loaded, the necessary ordering of "expand what the compiler knows about", (and only) then "compile code that uses that knowledge" was satisfied.

--Steve

Attachment: smime.p7s
Description: S/MIME cryptographic signature

Reply via email to