thunk.el 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. ;;; thunk.el --- Lazy form evaluation -*- lexical-binding: t -*-
  2. ;; Copyright (C) 2015-2017 Free Software Foundation, Inc.
  3. ;; Author: Nicolas Petton <nicolas@petton.fr>
  4. ;; Keywords: sequences
  5. ;; Version: 1.0
  6. ;; Package: thunk
  7. ;; Maintainer: emacs-devel@gnu.org
  8. ;; This file is part of GNU Emacs.
  9. ;; GNU Emacs is free software: you can redistribute it and/or modify
  10. ;; it under the terms of the GNU General Public License as published by
  11. ;; the Free Software Foundation, either version 3 of the License, or
  12. ;; (at your option) any later version.
  13. ;; GNU Emacs is distributed in the hope that it will be useful,
  14. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. ;; GNU General Public License for more details.
  17. ;; You should have received a copy of the GNU General Public License
  18. ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
  19. ;;; Commentary:
  20. ;;
  21. ;; Thunk provides functions and macros to delay the evaluation of
  22. ;; forms.
  23. ;;
  24. ;; Use `thunk-delay' to delay the evaluation of a form, and
  25. ;; `thunk-force' to evaluate it. The result of the evaluation is
  26. ;; cached, and only happens once.
  27. ;;
  28. ;; Here is an example of a form which evaluation is delayed:
  29. ;;
  30. ;; (setq delayed (thunk-delay (message "this message is delayed")))
  31. ;;
  32. ;; `delayed' is not evaluated until `thunk-force' is called, like the
  33. ;; following:
  34. ;;
  35. ;; (thunk-force delayed)
  36. ;;; Code:
  37. (defmacro thunk-delay (&rest body)
  38. "Delay the evaluation of BODY."
  39. (declare (debug t))
  40. (let ((forced (make-symbol "forced"))
  41. (val (make-symbol "val")))
  42. `(let (,forced ,val)
  43. (lambda (&optional check)
  44. (if check
  45. ,forced
  46. (unless ,forced
  47. (setf ,val (progn ,@body))
  48. (setf ,forced t))
  49. ,val)))))
  50. (defun thunk-force (delayed)
  51. "Force the evaluation of DELAYED.
  52. The result is cached and will be returned on subsequent calls
  53. with the same DELAYED argument."
  54. (funcall delayed))
  55. (defun thunk-evaluated-p (delayed)
  56. "Return non-nil if DELAYED has been evaluated."
  57. (funcall delayed t))
  58. (provide 'thunk)
  59. ;;; thunk.el ends here