Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't get pprint to work in clojure

Noob question, using Win7 64-bit, Clojure 1.2.0, Java 1.6.0_22

When I start clojure from command line, pprint function is easily available.

user=> pprint
#<pprint$pprint clojure.pprint$pprint@16dfa45>
user=> (pprint "hi")
"hi"
nil
user=>

But when I try to use pprint from a file, I get an error. This happens with and without namespace (ns... :require...) as shown in pprint documentation

clj file as follows:

(ns whatevah
(:require clojure.pprint))

(pprint "hi")

Error as follows:

C:\Users\mischw\code\Clojure>java -cp ";c:\users\mischw\code\clojure\classes\*;c:\Program Files (x86)\Java\SWT;c:\users\mischw\code\clojure\classes\bookcode\*" clojure.main swinglearn.clj 
Exception in thread "main" java.lang.Exception: Unable to resolve symbol: pprint in this context (swinglearn.clj:14)
... 21 more

Output completed (0 sec consumed) - Normal Termination

I don't understand the general idea of what's going on here. Why does one work but not the other? Does that have to do with namespaces? Classpaths? Some other simple fix? Clearly noob questions, but I find this happens with a bunch of examples... I'm unable to run them even though it seems straightforward to import/use/require/include them.

like image 835
Sonicsmooth Avatar asked Mar 11 '11 18:03

Sonicsmooth


1 Answers

You're getting require mixed up with use and/or import. require causes the library to get loaded, and every public symbol it exports will be accessible as eg clojure.pprint/pprint. If you want to use a more convenient name like just pprint, you need to refer to the namespace. use is a convenient shorthand for "require, then refer", to load the library without the namespace prefix.

user> (ns user (:require clojure.pprint))
nil
user> (pprint 1)
; Evaluation aborted.
user> (clojure.pprint/pprint 1)
1
nil
user> (ns user (:use clojure.pprint))
nil
user> (pprint 1)
1

Edit: Not sure why it's working for you from the REPL. As you can see, it doesn't work for me. I imagine you did some setup earlier that makes it work and then forgot about it, or possibly you have some init script that does this stuff for you at the REPL but not when loading from a file.

like image 127
amalloy Avatar answered Oct 05 '22 04:10

amalloy