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