|
225 | 225 |
|
226 | 226 |
|
227 | 227 | ;; "Lexical Scope" in Clojure |
228 | | -;; - Develop an intuition for what "Lexical scope" might mean |
229 | | -;; by reasoning about the following exercises. |
| 228 | +;; - Lexical scope guarantees that the reference to a value will be |
| 229 | +;; "enclosed" in the scope in which it is being used. |
| 230 | + |
| 231 | +(comment |
| 232 | + ;; Strict lexical scope greatly simplifies our life, because |
| 233 | + ;; it allows us to mechanically follow code, and determine |
| 234 | + ;; where a value originated. |
| 235 | + ;; - Start at the place of reference of the value. |
| 236 | + ;; - Then "walk" outwards, until you meet the very first let binding, |
| 237 | + ;; or arg-list, or def, where the value was bound. |
| 238 | + ;; - Now you know where the value came from. |
| 239 | + ;; |
| 240 | + ;; This also helps reduce our mental burden of inventing |
| 241 | + ;; new names to refer to things, because we can re-use |
| 242 | + ;; a name within a limited scope, and be certain that |
| 243 | + ;; it will not destroy anything with the same name outside |
| 244 | + ;; the given scope. |
| 245 | + ) |
230 | 246 |
|
231 | 247 | ;; EXERCISE: |
232 | | -;; Mentally evaluate and predict the results; then check. |
| 248 | +;; - Develop an intuition for what "Lexical scope" might mean |
| 249 | +;; by reasoning about the following exercises. |
| 250 | +;; |
| 251 | +;; - Mentally evaluate and predict the results; then check. |
233 | 252 |
|
234 | 253 | (def x 42) ; Bind `x` to 42, globally ("top-level" binding) |
235 | 254 |
|
|
293 | 312 | ((let [x 10] (fn [x] x)) x) |
294 | 313 |
|
295 | 314 |
|
296 | | -(comment |
297 | | - ;; Strict lexical scope greatly simplifies our life, because |
298 | | - ;; it allows us to mechanically work out where a value originated. |
299 | | - ;; - Start at the place of reference of the value. |
300 | | - ;; - Then "walk" outwards, until you meet the very first let binding, |
301 | | - ;; or argument list, or def, where the value was bound. |
302 | | - ;; - Now you know where the value came from. |
303 | | - ;; |
304 | | - ;; This also helps reduce our mental burden of inventing new names |
305 | | - ;; to refer to things, because we can re-use a name within a |
306 | | - ;; limited scope, and be certain that it will not destroy |
307 | | - ;; anything with the same name outside the given scope. |
308 | | - ) |
309 | | - |
310 | | - |
311 | 315 | ;; Function "Closure" |
312 | 316 | ;; - This is a way for a function to capture and "close over" |
313 | 317 | ;; any value available at the time the function is defined |
|
0 commit comments