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

multiple-values.lsp 1.8KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  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. "In lisp, it is possible for a function to return more than one value.
  15. This is distinct from returning a list or structure of values."
  16. (define-test test-floor-returns-multiple-values
  17. (let ((x)
  18. (y))
  19. (setf x (floor 1.5))
  20. (assert-equal x 1)
  21. (setf x (multiple-value-list (floor 3/2)))
  22. (assert-equal x '(1 1/2)))
  23. (assert-equal (multiple-value-list (floor 99/4)) '(24 3/4)))
  24. (defun next-fib (a b)
  25. (values b (+ a b)))
  26. (define-test test-multi-value-bind
  27. (let ((x)
  28. (y))
  29. (setf x (next-fib 2 3))
  30. (assert-equal x 3)
  31. (setf x (multiple-value-list (next-fib 2 3)))
  32. (assert-equal x '(3 5))
  33. "multiple-value-bind binds the variables in the first form
  34. to the outputs of the second form. And then returns the output
  35. of the third form using those bindings"
  36. (setf y (multiple-value-bind (b c) (next-fib 3 5) (* b c)))
  37. (assert-equal y 40)
  38. "multiple-value-setq is like setf, but can set multiple variables"
  39. (multiple-value-setq (x y) (values :v1 :v2))
  40. (assert-equal (list x y) '(:v1 :v2))
  41. (multiple-value-setq (x y) (next-fib 5 8))
  42. (assert-equal (list x y) '(8 13))))