Fork of https://github.com/google/lisp-koans so that I could go through them. THIS CONTAINS ANSWERS.

scope-and-extent.lsp 2.1KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. ;; Copyright 2013 Google Inc.
  2. ;;
  3. ;; Licensed under the Apache License, Version 2.0 (the "License");
  4. ;; you may not use this file except in compliance with the License.
  5. ;; You may obtain a copy of the License at
  6. ;;
  7. ;; http://www.apache.org/licenses/LICENSE-2.0
  8. ;;
  9. ;; Unless required by applicable law or agreed to in writing, software
  10. ;; distributed under the License is distributed on an "AS IS" BASIS,
  11. ;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. ;; See the License for the specific language governing permissions and
  13. ;; limitations under the License.
  14. (defun shadow-z (z)
  15. ;; reuses the symbol name z to build a return value
  16. ;; returns a list like (value-of-z, 2)
  17. (cons z
  18. (cons (let ((z 2)) z)
  19. nil)))
  20. (define-test test-shadowing-a-variable
  21. (assert-equal ___ (shadow-z 1)))
  22. (defun code-block-01 ()
  23. ;; illustrates a basic property of code-blocks
  24. (block here
  25. (return-from here 4)
  26. 5))
  27. (defun code-block-02 ()
  28. (block outer
  29. (block inner
  30. (return-from outer 'space)
  31. (return-from inner 'tube))
  32. (return-from outer 'valve)))
  33. (define-test test-code-block-01
  34. (assert-equal ___ (code-block-01)))
  35. (define-test test-code-block-02
  36. (assert-equal ___ (code-block-02)))
  37. ;; About closures and the distinction of lexical and dynamic bindings
  38. ;; this recipe from stackoverflow
  39. ;; http://stackoverflow.com/questions/463463/dynamic-and-lexical-variables-in-common-lisp
  40. ; (print "no special x: a typical closure.")
  41. ;; bind f to a function which depends on a local variable x
  42. ;; then invoke f to see which value of x is returned.
  43. (define-test test-lexical-bindings-may-be-shadowed
  44. (assert-eq ___ (let ((f (let ((x 10))
  45. (lambda () x)))) ; <-- x bound lexically
  46. (let ((x 20)) ; form 2
  47. (funcall f)))))
  48. (define-test test-special-bindings-look-back-on-execution-path
  49. (assert-eq ___ (let ((f (let ((x 10))
  50. (declare (special x))
  51. (lambda () x)))) ; <-- x bound dynamically
  52. (let ((x 20)) ; form 2
  53. (declare (special x))
  54. (funcall f)))))