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

control-statements.lsp 1.9KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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. (define-test test-if-then-else
  15. (let ((result))
  16. (if t
  17. (setf result "true value")
  18. (setf result "false value"))
  19. (assert-equal result ____)
  20. (if nil
  21. (setf result "true value")
  22. (setf result "false value"))
  23. (assert-equal result ____)))
  24. (define-test test-when-and-unless
  25. (let ((result-1 nil)
  26. (result-2 nil)
  27. (when-nums nil)
  28. (unless-nums nil))
  29. (dolist (x '(1 2 3 4 5 6 7 8 9 10))
  30. (when (> x 5)
  31. (setf result-1 x)
  32. (push x when-nums))
  33. (unless (> x 5)
  34. (setf result-2 x)
  35. (push x unless-nums)))
  36. (assert-equal result-1 ___)
  37. (assert-equal result-2 ___)
  38. (assert-equal when-nums ___)
  39. (assert-equal unless-nums ___)))
  40. (define-test test-and-short-circuits
  41. "and only evaluates forms until one evaluates to nil"
  42. (assert-equal
  43. ____
  44. (let ((x 0))
  45. (and
  46. (setf x (+ 1 x))
  47. (setf x (+ 1 x))
  48. nil ;; <- ends execution of and.
  49. (setf x (+ 1 x)))
  50. x)))
  51. (define-test test-or-also-short-circuits
  52. "or only evaluates until one argument evaluates to non-nil"
  53. (assert-equal
  54. ____
  55. (let ((x 0))
  56. (or
  57. (setf x (+ 1 x))
  58. (setf x (+ 1 x))
  59. nil
  60. (setf x (+ 1 x)))
  61. x)))