typestar

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

  1. pool-report opens a let where depth-m and width-m scale the centimeter arguments.
  2. surface and volume are bound further down and read those earlier locals.
  3. An inner let rebinds tide for the length of its body, and the outer value returns afterward.

Keywords and builtins used here

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.

Type this snippet

Step 2 of 3 in Values & bindings, step 2 of 27 in Language basics.

← Previous Next →