Namespaces

Web Development with Clojure, Third Edition — by Dmitri Sotnikov, Scot Brown (76 / 107)

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 Destructuring Data | TOC | Dynamic Variables 👉

When writing real-world applications, we need tools to organize our code into separate components. Object-oriented languages provide classes for this purpose. The related methods are all defined in the same class. In Clojure, we group our functions into namespaces instead. Let’s look at how a namespace is defined.

​ (​ns​ colors)

​ (​defn​ hex->rgb [[_ & rgb]]
​ (map #(​->>​ % (apply str ​"0x"​) (​Long/decode​))
​ (​partition​ 2 rgb)))

​ (​defn​ hex-str [n]
​ (-> (​format​ ​"%2s"​ (​Integer/toString​ n 16))
​ (​clojure.string/replace​ ​" "​ ​"0"​)))

​ (​defn​ rgb->hex [color]
​ (apply str ​"#"​ (map hex-str color)))

Preceding, we have a namespace called colors containing three functions called hex->rgb, hex-str, and rgb->hex. The functions in the same namespace can call each other directly. But if we wanted to call these functions from a different namespace, we’d have to reference the colors namespace there first.

Clojure provides two ways to do this: we can use either the :use or the :require keyword.

The :use Keyword

When we reference a namespace with :use, all its vars become implicitly available, as if they were defined in the namespace that references it.

--

--

The Pragmatic Programmers
The Pragmatic Programmers

We create timely, practical books and learning resources on classic and cutting-edge topics to help you practice your craft and accelerate your career.