A namespace groups related functions, vars, and other things. Without namespaces, different functions with the same names would interfere and cause problems. Even in a REPL, you always work within a namespace.
The repl prompt below is probably familiar to you already.
What is this
user? This is the default namespace when you start the repl.
Let’s create a new namespace. You can do this in three ways:
Advice to coaches
Please explain the differences of the three functions, perhaps by using the
doc function. If the namespace has been changed by
in-ns, you can call the
doc function using its namespace. For example:
You can confirm that var names are different in each namespace.
So far, we have learned how to create a namespace. The next step is to use namespaces. You will do this very often because almost all Clojure programs use some or many libraries. Every library groups functions into its own namespace.
To explore namespaces, we want to set up at least two different namespaces and different functions in those namespaces.
Create a Clojure project and write two Clojure files,
two.clj should be in the my-nses/src/my_nses directory.
my-nses/src └── my_nses ├── one.clj └── two.clj
Once the code is ready, start repl in the my-nses (top) directory.
To use our code, we have two choices:
For the first attempt, we will use the
As we tried,
use function loads the functions of the specified namespace(s) into
current namespace. If you have a duplicate function, that will result in an exception.
In the next attempt, we will use the
This resolves the error that happened above.
We tried just some of the namespace management functions. Clojure has more ways to avoid function name collision. If you’re not using a repl, requiring or using other namespaces is slightly different.
Please see references for details:
These are useful references, especially, the first is worth reading.
Clojure Libs and Namespaces: require, use, import, and ns
Clojure Namespaces and Vars
Clojure for the Brave and True, Organizing Your Project: a Librarian’s Tale, 3. Creating and Switching to Namespaces