let
Advice to coaches
The let binding is frequently used in function definitions. We have functions with destructuring and functions with let/destructuring sections. It may be good to come back to this lab after or during the function lab.
Like def
, let
creates a binding.
In other languages, it is called a local variable assignment.
In Clojure, it has the different name: lexical binding.
Similar to local variables in other languages, Clojure’s lexically bound variables are available to
use in a limited code block (scope).
However, unlike other languages, the values never change (immutable).
For convenience, this document uses the word variable but its value won’t vary once the value is assigned.
The syntax is (let [bindings*] exprs*)
.
Let’s try this in a REPL.
We can write as many bindings (key-value pairs) as we want within the square brackets. Those bindings are evaluated one by one, so we can use the evaluated result within a single square bracket. Try these examples below:
As seen in the examples above, the value part of bindings can be a function.
We can use println
function in let bindings, too.
This is often used for debugging so that you can check the value.
ClojureDocs
Introduction to Clojure, Let and Locals
http://clojure-doc.org/articles/tutorials/introduction.html#let-and-locals
Clojure from the ground up: functions, “Let bindings”
http://aphyr.com/posts/303-clojure-from-the-ground-up-functions
Clojure for the Brave and True, Do Things, 4.2 let