04 / 10
Names
def, let and defn, and what happens when a name is defined again.
Three forms give names to things. def names a value for the whole file, defn names a function, and let names values for the forms inside it.
def and defn
;; def names a value. defn names a function. (def seats 3) (def crew #["Alvin" "Hilvar"]) (defn free-seats [] (- seats (count crew))) ;; A ? ends a function that answers yes or no. (defn full? [] (= (free-seats) 0)) (defn main [args] (print "free seats:" (free-seats)) (print "full?" (full?)))
Try it: Add "Alystra" to crew. Both lines change, and you touched neither function.
Names are written in lower case with hyphens: free-seats. A name may end in ?, and by habit that is a function that answers yes or no. One that ends in ! changes something, and since values do not change, you will not see many.
let
let takes pairs, a name and then its value, and the forms that use them. The names exist only inside the let.
(defn describe [width height] ;; let names values for the forms inside it. ;; A later name may use an earlier one. (let [area (* width height) size (if (> area 20) "large" "small")] f"{width} by {height}: {area}, {size}")) (defn main [args] (print (describe 3 4)) (print (describe 6 5)) ;; let is an expression: it gives the value of its last form. (print (let [x 2] (* x x))) ;; A name defined again inside covers the one outside, and only there. (let [x 1] (let [x 100] (print "inside:" x)) (print "outside:" x)))
Try it: Print area from main, outside its let. Diaspar warns before the program starts, and stops when it gets there.
A name cannot be assigned a second time. Inside a let you can give the same name to a new value, and outside the old one is untouched. A place that really changes is a different thing, with a different name, and comes later in the tour.
Defining a name again
At the top of a file, or in a session, a name can be defined again. This is how a program is changed while it runs. Below, welcome calls greet. Then greet is defined a second time, and welcome is left alone.
(defn greet [name] f"hi, {name}") (defn welcome [name] (str (greet name) ", come in")) (def before (welcome "Alvin")) ;; greet is defined again. welcome is not touched. (defn greet [name] f"welcome back, {name}") (defn main [args] (print before) (print (welcome "Alvin")))
Try it: Delete the second greet. Both lines say the same.
The first line was computed before the change and kept its old text. The second call of welcome found the new greet. Nothing was compiled again and nothing was restarted.
A name that is not there
A misspelled name is found when the file is read, before anything runs, and the report suggests the name you meant.
(def seats 3) (defn main [args] (print "seats:" seats) (print "free:" (- saets 1)))
Try it: Fix the name. The warning and the error both go away.
It is a warning, and the program still starts: it printed its first line. The error came when the line with the unknown name ran.