Anton Harald
Anton Harald

Reputation: 5944

why some native clojure namespaces have to be required and some not

Simple as the headline suggest:

Why do I have to

(require 'clojure.edn)

in order to use e.g.:

(clojure.edn/read-string "9")

And why can I immediately invoke:

(clojure.string/join (range 4) "-")

Upvotes: 5

Views: 234

Answers (2)

Arthur Ulfeldt
Arthur Ulfeldt

Reputation: 91554

Clojure programs start at the top of the "main" namespace (often project-name.core) and evaluate each form from top to bottom. This happens when the program starts, and before any "main" functions are invoked.

When a require expression is evaluated it jumps over to that namespace and does the same thing there. If requires are encountered there it recurses down branches of those namespaces, recursively loading each namespace as required.

So If you don't explicitly state that your namespace requires another namespace, then you are at the mercy of the order that other namspaces you require load their dependencies. Sometimes it will work, and sometimes unrelated changes to the evaulation order of your distant dependencies will break your code.

So please, please, ... declare your own requirements!

Upvotes: 8

birdspider
birdspider

Reputation: 3074

in the repl (just starting clojure) I have the following ns loaded by default

user=> (pprint (map #(.getName %) (all-ns)))
(clojure.edn
 clojure.core.server
 clojure.java.io
 clojure.java.shell
 clojure.core.protocols
 clojure.string
 clojure.java.browse
 clojure.pprint
 clojure.uuid
 clojure.core
 clojure.main
 user
 clojure.java.javadoc
 clojure.repl
 clojure.walk
 clojure.instant)

in whichever namespace you are in, clojure.edn seems not to be loaded

Upvotes: 1

Related Questions