Welcome! Please see the About page for a little more info on how this works.

0 votes
in Docs by

Hi,
Having been a longtime happy and satisfied user of Clojure I realized that there is very little to introduce someone new to Clojure to closures where functions [like vehicles] are passed in with opaqueness to their variables [like passengers] to another function. I think this is probably a stumbling block for many beginners and might even, unfortunately, discourage people from adopting the language without further explanation of this caveat. I think many programmers will also disagree with my assessment because they have "closure eyes" and can transparently understand passing functions around as first-class-citizens so-to-speak.

I propose that we amend the documentation to explicitly mention that closures are basically like vehicles or cars with passengers.

the fact that not everything is transparent to the top level function call is something non-obvious


(defn make-adder [x]
 (fn [y] (+ x y)))

(def add5 (make-adder 5))
 (add5 10) ;; Returns 15

In this example:

make-adder is like a vehicle factory. When you call it with 5, it creates a new vehicle.
This new vehicle (the returned function) has a permanent passenger: the value 5 is sitting in the x seat.

There's one empty seat (y) that you can fill when you drive the vehicle (call the function).

When you call (add5 10), you're putting 10 in the y seat and driving the vehicle.

Inside, the passengers interact: x (which is 5) and y (which is 10) are added together.


How REPLs and Closures Intertwine
The REPL (Read-Eval-Print-Loop) and closures interact in interesting ways:

Creation and Persistence:
When you define (def add5 (make-adder 5)) in the REPL, you're parking a vehicle (with 5 already inside) in your garage with the name "add5". This vehicle persists between REPL evaluations.
Inspection Limitations:
In the REPL, you can see that add5 is a function, but you can't directly inspect who's sitting inside it. If you evaluate add5, you'll just see something like #function[user/make-adder/fn--123].
Usage in REPL:
You can use the closure by calling it: (add5 10). The REPL will evaluate this by driving the vehicle with 10 in the y seat, and print the result (15).

by
This strikes me as a good idea for a blog post.

1 Answer

+1 vote
by

Whist metaohor and analogy can be useful additions, they are subjective and not always understood. Personally I found it hard to relate to a garage containing cars with 5 people already in the car (how are more people going to get into the car, maybe it should be a bus)

Writing a more detailed article around the example above would allow more people (especially those new to Clojure) to give feedback, providing a much broader view.

...