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

variables-parameters-constants.lsp 2.3KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. (defun test-variable-assignment-with-setf ()
  2. ;; the let pattern allows us to create local variables with
  3. ;; lexical scope.
  4. (let (var_name_1 (var_name_2 "Michael"))
  5. ;; variables may be defined with or without initial values.
  6. (and
  7. (equalp var_name_2 "Michael")
  8. ; new values may be assigned to variables with setf
  9. (setf var_name_2 "Janet")
  10. (equalp var_name_2 "Janet")
  11. ; setf may assign multiple variables in one form.
  12. (setf var_name_1 "Tito"
  13. var_name_2 "Jermaine")
  14. (equalp var_name_1 "Tito")
  15. (equalp var_name_2 "Jermaine"))))
  16. (defun test-setf-for-lists ()
  17. ;; setf also works on list elements
  18. (let (l)
  19. (setf l '(1 2 3))
  20. (equalp l '(1 2 3))
  21. ; First second and third are convenient accessor functions
  22. ; referring to the elements of a list
  23. ; For those interested, they are convenient to car, cadr, and caddr
  24. (setf (first l) 10)
  25. (setf (second l) 20)
  26. (setf (third l) 30)
  27. (equalp l '(10 20 30))))
  28. (defparameter param_name_1 "Janet")
  29. ; defparameter requires an initial form. It is a compiler error to exclude it
  30. ;(defparameter param_no_init) ;; this will fail
  31. (defconstant additive_identity 0)
  32. ; defconstant also requires an initial form
  33. ; (defconstant constant_no_init)
  34. ; reassigning parameters to new values is also ok, but parameters carry the
  35. ; connotation of immutability. If it's going to change frequently, it should
  36. ; be a var.
  37. (setf param_name_1 "The other one")
  38. ; reassigning a constant is an error.
  39. ; this should result in a compile time error
  40. ; (setf additive_identity -1)
  41. ;; -------------------------------
  42. ;; below is necessary to run tests.
  43. ;; -------------------------------
  44. (defvar failed-test-names nil)
  45. (defun run-test (testfun)
  46. (let ((fun-name (function-name testfun)))
  47. (if (apply testfun '())
  48. (format t ".")
  49. (progn
  50. (setf failed-test-names (cons fun-name failed-test-names))
  51. (format t "F")))))
  52. (defun function-name (function) (nth-value 2 (function-lambda-expression function)))
  53. (run-test #'test-variable-assignment-with-setf)
  54. (run-test #'test-setf-for-lists)
  55. (format t "~%")
  56. (defun report-failure (test-name)
  57. (format t "~S failed.~%" test-name))
  58. (if (endp failed-test-names) ; no failed tests
  59. (format t "all tests pass.~%")
  60. (mapcar #'report-failure failed-test-names))