Reading: Clojure for the Brave – ch 6

Chapter 6

Symbols and Vars

  • vars are the memory address that contains the value and symbols are a human-friendly name for that address
  • Given a symbol, clojure tries to find a var corresponding to it in the current namespace
  • If you want to use the symbol and not the var it refers to, then you have to quote it (either using quote or ')
(def books ["b1" "b2"])
; => #'user/books

books
; => ["b1" "b2"]

This code tells Clojure:

  1. Update the current namespace’s map with the association between books and the var.
  2. Find a free storage in memory and store ["a" "b"] in it
  3. Write the found address back into the var.
  4. Return the var (in this case, #'user/books).

This process is called interning a var. You can interact with a namespace’s map of symbols-to-interned-vars using ns-interns. #'user/great-books is the reader form of a var

(deref #'user/books) tells clojure: ““Get the shelf number from the var, go to that shelf number, grab what’s on it, and give it to me!”

clojure.core/refer

  • To use symbols defined in another ns use (com.microsoft/sql-server) use an object defined in com.microsoft namespace named sql-server
  • (clojure.core/refer ‘my-namespace) allows me to use symbols defined in my-namespace without fully-qualifying it.
  • When you call refer, you can also pass it the filters :only, :exclude, and :rename. As the names imply, :only and :exclude restrict which symbol/var mappings get merged into the current namespace’s ns-map. :rename lets you use different symbols for the vars being merged in.
  • (defn- ) defines a private function which isn’t visible to the clients referring to the namespace

clojure.core/alias

 (clojure.core/alias 'taxonomy 'cheese.taxonomy)

This code lets us use call symbols from the cheese.taxonomy namespace with the shorter alias taxonomy.

(require '[the-divine-cheese-code.visualization.svg 
          :as svg])

;; Equivalent to
(require 'the-divine-cheese-code.visualization.svg)
(alias 'svg 'the-divine-cheese-code.visualization.svg)

Similarly:

(use 'the-divine-cheese-code.visualization.svg)
;; Equivalent to
(require 'the-divine-cheese-code.visualization.svg)
(refer 'the-divine-cheese-code.visualization.svg)

clojure.core/use


Advertisement