philipbohun.com

Glojure by Example: Closures

A function closes over the bindings in scope where it was created. adder returns a new function that remembers n.

(defn adder [n]
  (fn [x] (+ x n)))

(def add3 (adder 3))
(println (add3 4))

The closed-over value is the binding's value. A closure can also close over a collection and hand back a view of it.

(defn prefixes [items]
  (fn [n] (vec (take n items))))

(def take-letters (prefixes ["a" "b" "c" "d"]))
(println (take-letters 2))

The returned function keeps the values it closed over.

$ glj closures.glj
7
[a b]

Next example: Recursion.