Optimize DELETE-FROM-PLIST not to cons.
[alexandria.git] / binding.lisp
blob36d92bce0b7bf29a7803d6a0fc8473ddbb9f210a
1 (in-package :alexandria)
3 (defmacro if-let (bindings &body (then-form &optional else-form))
4 "Creates new variable bindings, and conditionally executes either
5 THEN-FORM or ELSE-FORM. ELSE-FORM defaults to NIL.
7 BINDINGS must be either single binding of the form:
9 (variable initial-form)
11 or a list of bindings of the form:
13 ((variable-1 initial-form-1)
14 (variable-2 initial-form-2)
15 ...
16 (variable-n initial-form-n))
18 All initial-forms are executed sequentially in the specified order. Then all
19 the variables are bound to the corresponding values.
21 If all variables were bound to true values, the THEN-FORM is executed with the
22 bindings in effect, otherwise the ELSE-FORM is executed with the bindings in
23 effect."
24 (let* ((binding-list (if (and (consp bindings) (symbolp (car bindings)))
25 (list bindings)
26 bindings))
27 (variables (mapcar #'car binding-list)))
28 `(let ,binding-list
29 (if (and ,@variables)
30 ,then-form
31 ,else-form))))
33 (defmacro when-let (bindings &body forms)
34 "Creates new variable bindings, and conditionally executes FORMS.
36 BINDINGS must be either single binding of the form:
38 (variable initial-form)
40 or a list of bindings of the form:
42 ((variable-1 initial-form-1)
43 (variable-2 initial-form-2)
44 ...
45 (variable-n initial-form-n))
47 All initial-forms are executed sequentially in the specified order. Then all
48 the variables are bound to the corresponding values.
50 If all variables were bound to true values, then FORMS are executed as an
51 implicit PROGN."
52 (let* ((binding-list (if (and (consp bindings) (symbolp (car bindings)))
53 (list bindings)
54 bindings))
55 (variables (mapcar #'car binding-list)))
56 `(let ,binding-list
57 (when (and ,@variables)
58 ,@forms))))
60 (defmacro when-let* (bindings &body forms)
61 "Creates new variable bindings, and conditionally executes FORMS.
63 BINDINGS must be either single binding of the form:
65 (variable initial-form)
67 or a list of bindings of the form:
69 ((variable-1 initial-form-1)
70 (variable-2 initial-form-2)
71 ...
72 (variable-n initial-form-n))
74 Each initial-form is executed in turn, and the variable bound to the
75 corresponding value. Initial-form expressions can refer to variables
76 previously bound by the WHEN-LET*.
78 Execution of WHEN-LET* stops immediately if any initial-form evaluates to NIL.
79 If all initial-forms evaluate to true, then FORMS are executed as an implicit
80 PROGN."
81 (let ((binding-list (if (and (consp bindings) (symbolp (car bindings)))
82 (list bindings)
83 bindings)))
84 (labels ((bind (bindings forms)
85 (if bindings
86 `((let (,(car bindings))
87 (when ,(caar bindings)
88 ,@(bind (cdr bindings) forms))))
89 forms)))
90 `(let (,(car binding-list))
91 (when ,(caar binding-list)
92 ,@(bind (cdr binding-list) forms))))))