Clojure, lesson 2
Programs work with values: numbers, text, true or false. To refer to a value by name, Clojure
gives you two tools: def for names the whole file can see, and let for names that only live
inside one expression.
def: top-level names(def city "Lyon")
(def population 522000)
(def rainy? true)
(println city population) ; Lyon 522000def creates a var, a named slot at the top level of your namespace. Names are written in
kebab-case (words joined by dashes), and names of true/false values often end with ?. Clojure
allows many characters in names that other languages don't: rainy?, total-price, ->celsius.
Clojure works out types at run time, so you never declare them:
| Kind | Examples | Notes |
|---|---|---|
| integer | 42, -7 | 64-bit whole numbers |
| decimal | 3.14, 2.0 | 64-bit floating point |
| ratio | 1/3 | exact fractions |
| string | "hello" | text in double quotes |
| character | \a, \space | a single character |
| boolean | true, false | |
| nil | nil | "no value" |
| keyword | :red, :size | a name that stands for itself, used as a label |
str turns anything into a string and joins the results, and count tells you how long a string
is:
In Clojure, values are immutable. The number 3, the string "Lyon" and, as you will see
later, whole lists and maps cannot be modified. Functions that look like they change something
actually return a new value. This sounds restrictive, but it means a value you are holding can
never be changed behind your back by some other part of the program.
def can technically be repeated to point a name somewhere else, but that is meant for
experimenting, not for normal program logic. Treat each def as a constant: define it once, near
the top of the file.
let: local namesMost names in real code are local. let takes a vector of name/value pairs, followed by a body
that can use them:
Each name can use the ones defined before it (area uses width and height). The names exist
only inside the let's parentheses. The value of the whole let is the value of its last form,
because in Clojure every form returns a value.
If you let a name that already exists, the new one shadows the old one inside the body.
Nothing is overwritten: outside the let, the old meaning is still there.
2 exercises to try what you just read.
(str "Apples: " 3) ; "Apples: 3"
(count "Clojure") ; 7(let [width 8
height 5
area (* width height)]
(println "Area:" area))Total: 300Ada
LovelaceLovelace, Ada
Letters: 11