]> code.delx.au - gnu-emacs/blob - lisp/emacs-lisp/thunk.el
New library thunk.el
[gnu-emacs] / lisp / emacs-lisp / thunk.el
1 ;;; thunk.el --- Lazy form evaluation -*- lexical-binding: t -*-
2
3 ;; Copyright (C) 2015 Free Software Foundation, Inc.
4
5 ;; Author: Nicolas Petton <nicolas@petton.fr>
6 ;; Keywords: sequences
7 ;; Version: 1.0
8 ;; Package: thunk
9
10 ;; Maintainer: emacs-devel@gnu.org
11
12 ;; This file is part of GNU Emacs.
13
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.
18
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.
23
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/>.
26
27 ;;; Commentary:
28 ;;
29 ;; Thunk provides functions and macros to control the evaluation of
30 ;; forms. Use `thunk-delay' to delay the evaluation of a form, and
31 ;; `thunk-force' to evaluate it. Evaluation is cached, and only
32 ;; happens once.
33
34 ;; Tests are located at test/automated/thunk-tests.el
35
36 ;;; Code:
37
38 (defmacro thunk-delay (&rest body)
39 "Delay the evaluation of BODY."
40 (declare (debug t))
41 (let ((forced (make-symbol "forced"))
42 (val (make-symbol "val")))
43 `(let (,forced ,val)
44 (lambda (&optional check)
45 (if check
46 ,forced
47 (unless ,forced
48 (setf ,val (progn ,@body))
49 (setf ,forced t)))
50 ,val))))
51
52 (defun thunk-force (delayed)
53 "Force the evaluation of DELAYED.
54 The result is cached and will be returned on subsequent calls
55 with the same DELAYED argument."
56 (funcall delayed))
57
58 (defun thunk-evaluated-p (delayed)
59 "Return non-nil if DELAYED has been evaluated."
60 (funcall delayed t))
61
62 (provide 'thunk)
63 ;;; thunk.el ends here