Chapter 1.9 --- Extra Credit
"Everything is theoretically impossible, until it is done."
One of the neater features of Lisp that result from lexical scope are Closures---you may have even heard of them before, since "closure" has been a big buzz-word in the tech world lately---particularly in the Node.js community. In the jargon of Computer Science, a Closure is a lambda expression (or, anonymous function), which has its open bindings bound in the lexical environment where it was defined. For now, you can think of them as a means to preserve state in functional programming.
In this chapter we will further explore the concepts of dynamic and lexical scope, introduce the concept of first-class functions, and walk through a number of interesting examples of Closures to make sure you have a good understanding of their use and potential. You'll also get a sneak peak at functions, giving you more confidence in the material before you tackle the next chapter!
Lexical Environments and Scope
;; let's look at lexical scoping (let ((one 1)) (let ((two (+ one one))) (let ((three (+ one two))) (let ((one 1.0)) (+ one two three))))) 6.0
(let ((one 1) (two 2) (three 3)) (- three two one))
LET*: Nested Lexical Scope
(let* ((one 1) (two (+ one one)) (three (+ two one))) (* three three))
- No side-effects
- No reliance on external state
- Same input => same output, every time
Functions can be passed as an argument to another function.
(map 'vector #'+ '(1 2 3 4) '(10 20 30 40))
Functors: Function Objects
LABEL and BLOCK
Functions as Arguments
Your First Closure
The Macroexpansion of DEFUN
Extending Closures: Continuations
Extending Closures: Partials