let locals in Clojure
Converts tide pool measurements inside a let, then watches a shadowed name snap back.
;; let binds locals in order, so later ones can use earlier ones
(defn pool-report [depth-cm width-cm]
(let [depth-m (/ depth-cm 100.0)
width-m (/ width-cm 100.0)
surface (* width-m width-m)
volume (* surface depth-m)]
(str "surface " surface " m2, volume " volume " m3")))
;; a rebinding shadows the outer one only inside its own body
(let [tide "low"]
(println "outside:" tide)
(let [tide "high"]
(println "inside:" tide))
(println "outside again:" tide))
(println (pool-report 18 60))
How it works
pool-reportopens aletwheredepth-mandwidth-mscale the centimeter arguments.surfaceandvolumeare bound further down and read those earlier locals.- An inner
letrebindstidefor the length of its body, and the outer value returns afterward.
Keywords and builtins used here
defnletprintlnstr
The run, in numbers
- Lines
- 16
- Characters to type
- 489
- Tokens
- 84
- Three-star pace
- 75 tpm
At the three-star pace of 75 tokens a minute, this run takes about 67 seconds.
Step 2 of 3 in Values & bindings, step 2 of 27 in Language basics.