]> code.delx.au - gnu-emacs/blob - lisp/cl.el
(defsetf): Use eval-and-compile for self-update-fn.
[gnu-emacs] / lisp / cl.el
1 ;; Common-Lisp extensions for GNU Emacs Lisp.
2 ;; Copyright (C) 1987, 1988, 1989, 1992 Free Software Foundation, Inc.
3
4 ;; Author: Cesar Quiroz <quiroz@cs.rochester.edu>
5 ;; Keywords: extensions
6
7 (defvar cl-version "3.0 07-February-1993")
8
9 ;; This file is part of GNU Emacs.
10
11 ;; GNU Emacs is distributed in the hope that it will be useful,
12 ;; but WITHOUT ANY WARRANTY. No author or distributor
13 ;; accepts responsibility to anyone for the consequences of using it
14 ;; or for whether it serves any particular purpose or works at all,
15 ;; unless he says so in writing. Refer to the GNU Emacs General Public
16 ;; License for full details.
17
18 ;; Everyone is granted permission to copy, modify and redistribute
19 ;; GNU Emacs, but only under the conditions described in the
20 ;; GNU Emacs General Public License. A copy of this license is
21 ;; supposed to have been given to you along with GNU Emacs so you
22 ;; can know your rights and responsibilities. It should be in a
23 ;; file named COPYING. Among other things, the copyright notice
24 ;; and this notice must be preserved on all copies.
25
26 ;;; Notes from Rob Austein on his mods
27 ;; yaya:/usr/u/sra/cl/cl.el, 5-May-1991 16:01:34, sra
28 ;;
29 ;; Slightly hacked copy of cl.el 2.0 beta 27.
30 ;;
31 ;; Various minor performance improvements:
32 ;; a) Don't use MAPCAR when we're going to discard its results.
33 ;; b) Make various macros a little more clever about optimizing
34 ;; generated code in common cases.
35 ;; c) Fix DEFSETF to expand to the right code at compile-time.
36 ;; d) Make various macros cleverer about generating reasonable
37 ;; code when compiled, particularly forms like DEFSTRUCT which
38 ;; are usually used at top-level and thus are only compiled if
39 ;; you use Hallvard Furuseth's hacked bytecomp.el.
40 ;;
41 ;; New features: GETF, REMF, and REMPROP.
42 ;;
43 ;; Notes:
44 ;; 1) I'm sceptical about the FBOUNDP checks in SETF. Why should
45 ;; the SETF expansion fail because the SETF method isn't defined
46 ;; at compile time? Lisp is going to check for a binding at run-time
47 ;; anyway, so maybe we should just assume the user's right here.
48
49 ;;; Commentary:
50
51 ;;;; These are extensions to Emacs Lisp that provide some form of
52 ;;;; Common Lisp compatibility, beyond what is already built-in
53 ;;;; in Emacs Lisp.
54 ;;;;
55 ;;;; When developing them, I had the code spread among several files.
56 ;;;; This file 'cl.el' is a concatenation of those original files,
57 ;;;; minus some declarations that became redundant. The marks between
58 ;;;; the original files can be found easily, as they are lines that
59 ;;;; begin with four semicolons (as this does). The names of the
60 ;;;; original parts follow the four semicolons in uppercase, those
61 ;;;; names are GLOBAL, SYMBOLS, LISTS, SEQUENCES, CONDITIONALS,
62 ;;;; ITERATIONS, MULTIPLE VALUES, ARITH, SETF and DEFSTRUCT. If you
63 ;;;; add functions to this file, you might want to put them in a place
64 ;;;; that is compatible with the division above (or invent your own
65 ;;;; categories).
66 ;;;;
67 ;;;; To compile this file, make sure you load it first. This is
68 ;;;; because many things are implemented as macros and now that all
69 ;;;; the files are concatenated together one cannot ensure that
70 ;;;; declaration always precedes use.
71 ;;;;
72 ;;;; Bug reports, suggestions and comments,
73 ;;;; to quiroz@cs.rochester.edu
74
75 \f
76 ;;;; GLOBAL
77 ;;;; This file provides utilities and declarations that are global
78 ;;;; to Common Lisp and so might be used by more than one of the
79 ;;;; other libraries. Especially, I intend to keep here some
80 ;;;; utilities that help parsing/destructuring some difficult calls.
81 ;;;;
82 ;;;;
83 ;;;; Cesar Quiroz @ UofR DofCSc - Dec. 1986
84 ;;;; (quiroz@cs.rochester.edu)
85
86 ;;; Too many pieces of the rest of this package use psetq. So it is unwise to
87 ;;; use here anything but plain Emacs Lisp! There is a neater recursive form
88 ;;; for the algorithm that deals with the bodies.
89
90 ;;; Code:
91
92 ;;; This version is due to Hallvard Furuseth (hallvard@ifi.uio.no, 6 Jul 91)
93 (defmacro psetq (&rest args)
94 "(psetq {VARIABLE VALUE}...): In parallel, set each VARIABLE to its VALUE.
95 All the VALUEs are evaluated, and then all the VARIABLEs are set.
96 Aside from order of evaluation, this is the same as `setq'."
97 ;; check there is a reasonable number of forms
98 (if (/= (% (length args) 2) 0)
99 (error "Odd number of arguments to `psetq'"))
100 (setq args (copy-sequence args)) ;for safety below
101 (prog1 (cons 'setq args)
102 (while (progn (if (not (symbolp (car args)))
103 (error "`psetq' expected a symbol, found '%s'."
104 (prin1-to-string (car args))))
105 (cdr (cdr args)))
106 (setcdr args (list (list 'prog1 (nth 1 args)
107 (cons 'setq
108 (setq args (cdr (cdr args))))))))))
109 \f
110 ;;; utilities
111 ;;;
112 ;;; pair-with-newsyms takes a list and returns a list of lists of the
113 ;;; form (newsym form), such that a let* can then bind the evaluation
114 ;;; of the forms to the newsyms. The idea is to guarantee correct
115 ;;; order of evaluation of the subforms of a setf. It also returns a
116 ;;; list of the newsyms generated, in the corresponding order.
117
118 (defun pair-with-newsyms (oldforms)
119 "PAIR-WITH-NEWSYMS OLDFORMS
120 The top-level components of the list oldforms are paired with fresh
121 symbols, the pairings list and the newsyms list are returned."
122 (do ((ptr oldforms (cdr ptr))
123 (bindings '())
124 (newsyms '()))
125 ((endp ptr) (values (nreverse bindings) (nreverse newsyms)))
126 (let ((newsym (gentemp)))
127 (setq bindings (cons (list newsym (car ptr)) bindings))
128 (setq newsyms (cons newsym newsyms)))))
129
130 (defun zip-lists (evens odds)
131 "Merge two lists EVENS and ODDS, taking elts from each list alternatingly.
132 EVENS and ODDS are two lists. ZIP-LISTS constructs a new list, whose
133 even numbered elements (0,2,...) come from EVENS and whose odd
134 numbered elements (1,3,...) come from ODDS.
135 The construction stops when the shorter list is exhausted."
136 (do* ((p0 evens (cdr p0))
137 (p1 odds (cdr p1))
138 (even (car p0) (car p0))
139 (odd (car p1) (car p1))
140 (result '()))
141 ((or (endp p0) (endp p1))
142 (nreverse result))
143 (setq result
144 (cons odd (cons even result)))))
145
146 (defun unzip-list (list)
147 "Extract even and odd elements of LIST into two separate lists.
148 The argument LIST is separated in two strands, the even and the odd
149 numbered elements. Numbering starts with 0, so the first element
150 belongs in EVENS. No check is made that there is an even number of
151 elements to start with."
152 (do* ((ptr list (cddr ptr))
153 (this (car ptr) (car ptr))
154 (next (cadr ptr) (cadr ptr))
155 (evens '())
156 (odds '()))
157 ((endp ptr)
158 (values (nreverse evens) (nreverse odds)))
159 (setq evens (cons this evens))
160 (setq odds (cons next odds))))
161 \f
162 (defun reassemble-argslists (argslists)
163 "(reassemble-argslists ARGSLISTS) => a list of lists
164 ARGSLISTS is a list of sequences. Return a list of lists, the first
165 sublist being all the entries coming from ELT 0 of the original
166 sublists, the next those coming from ELT 1 and so on, until the
167 shortest list is exhausted."
168 (let* ((minlen (apply 'min (mapcar 'length argslists)))
169 (result '()))
170 (dotimes (i minlen (nreverse result))
171 ;; capture all the elements at index i
172 (setq result
173 (cons (mapcar (function (lambda (sublist) (elt sublist i)))
174 argslists)
175 result)))))
176
177 \f
178 ;;; Checking that a list of symbols contains no duplicates is a common
179 ;;; task when checking the legality of some macros. The check for 'eq
180 ;;; pairs can be too expensive, as it is quadratic on the length of
181 ;;; the list. I use a 4-pass, linear, counting approach. It surely
182 ;;; loses on small lists (less than 5 elements?), but should win for
183 ;;; larger lists. The fourth pass could be eliminated.
184 ;;; 10 dec 1986. Emacs Lisp has no REMPROP, so I just eliminated the
185 ;;; 4th pass.
186 ;;;
187 ;;; [22 April 1991, sra] REMPROP now in library, so restored 4th pass.
188 (defun duplicate-symbols-p (list)
189 "Find all symbols appearing more than once in LIST.
190 Return a list of all such duplicates; `nil' if there are no duplicates."
191 (let ((duplicates '()) ;result built here
192 (propname (gensym)) ;we use a fresh property
193 )
194 ;; check validity
195 (unless (and (listp list)
196 (every 'symbolp list))
197 (error "a list of symbols is needed"))
198 ;; pass 1: mark
199 (dolist (x list)
200 (put x propname 0))
201 ;; pass 2: count
202 (dolist (x list)
203 (put x propname (1+ (get x propname))))
204 ;; pass 3: collect
205 (dolist (x list)
206 (if (> (get x propname) 1)
207 (setq duplicates (cons x duplicates))))
208 ;; pass 4: unmark.
209 (dolist (x list)
210 (remprop x propname))
211 ;; return result
212 duplicates))
213
214 ;;;; end of cl-global.el
215 \f
216 ;;;; SYMBOLS
217 ;;;; This file provides the gentemp function, which generates fresh
218 ;;;; symbols, plus some other minor Common Lisp symbol tools.
219 ;;;;
220 ;;;; Cesar Quiroz @ UofR DofCSc - Dec. 1986
221 ;;;; (quiroz@cs.rochester.edu)
222
223 ;;; Keywords. There are no packages in Emacs Lisp, so this is only a
224 ;;; kludge around to let things be "as if" a keyword package was around.
225
226 (defmacro defkeyword (x &optional docstring)
227 "Make symbol X a keyword (symbol whose value is itself).
228 Optional second argument is a documentation string for it."
229 (cond ((symbolp x)
230 (list 'defconst x (list 'quote x) docstring))
231 (t
232 (error "`%s' is not a symbol" (prin1-to-string x)))))
233
234 (defun keywordp (sym)
235 "t if SYM is a keyword."
236 (if (and (symbolp sym) (char-equal (aref (symbol-name sym) 0) ?\:))
237 ;; looks like one, make sure value is right
238 (set sym sym)
239 nil))
240
241 (defun keyword-of (sym)
242 "Return a keyword that is naturally associated with symbol SYM.
243 If SYM is keyword, the value is SYM.
244 Otherwise it is a keyword whose name is `:' followed by SYM's name."
245 (cond ((keywordp sym)
246 sym)
247 ((symbolp sym)
248 (let ((newsym (intern (concat ":" (symbol-name sym)))))
249 (set newsym newsym)))
250 (t
251 (error "expected a symbol, not `%s'" (prin1-to-string sym)))))
252 \f
253 ;;; Temporary symbols.
254 ;;;
255
256 (defvar *gentemp-index* 0
257 "Integer used by gentemp to produce new names.")
258
259 (defvar *gentemp-prefix* "T$$_"
260 "Names generated by gentemp begin with this string by default.")
261
262 (defun gentemp (&optional prefix oblist)
263 "Generate a fresh interned symbol.
264 There are 2 optional arguments, PREFIX and OBLIST. PREFIX is the
265 string that begins the new name, OBLIST is the obarray used to search for
266 old names. The defaults are just right, YOU SHOULD NEVER NEED THESE
267 ARGUMENTS IN YOUR OWN CODE."
268 (if (null prefix)
269 (setq prefix *gentemp-prefix*))
270 (if (null oblist)
271 (setq oblist obarray)) ;default for the intern functions
272 (let ((newsymbol nil)
273 (newname))
274 (while (not newsymbol)
275 (setq newname (concat prefix *gentemp-index*))
276 (setq *gentemp-index* (+ *gentemp-index* 1))
277 (if (not (intern-soft newname oblist))
278 (setq newsymbol (intern newname oblist))))
279 newsymbol))
280 \f
281 (defvar *gensym-index* 0
282 "Integer used by gensym to produce new names.")
283
284 (defvar *gensym-prefix* "G$$_"
285 "Names generated by gensym begin with this string by default.")
286
287 (defun gensym (&optional prefix)
288 "Generate a fresh uninterned symbol.
289 There is an optional argument, PREFIX. PREFIX is the
290 string that begins the new name. Most people take just the default,
291 except when debugging needs suggest otherwise."
292 (if (null prefix)
293 (setq prefix *gensym-prefix*))
294 (let ((newsymbol nil)
295 (newname ""))
296 (while (not newsymbol)
297 (setq newname (concat prefix *gensym-index*))
298 (setq *gensym-index* (+ *gensym-index* 1))
299 (if (not (intern-soft newname))
300 (setq newsymbol (make-symbol newname))))
301 newsymbol))
302
303 ;;;; end of cl-symbols.el
304 \f
305 ;;;; CONDITIONALS
306 ;;;; This file provides some of the conditional constructs of
307 ;;;; Common Lisp. Total compatibility is again impossible, as the
308 ;;;; 'if' form is different in both languages, so only a good
309 ;;;; approximation is desired.
310 ;;;;
311 ;;;; Cesar Quiroz @ UofR DofCSc - Dec. 1986
312 ;;;; (quiroz@cs.rochester.edu)
313
314 ;;; indentation info
315 (put 'case 'lisp-indent-hook 1)
316 (put 'ecase 'lisp-indent-hook 1)
317 (put 'when 'lisp-indent-hook 1)
318 (put 'unless 'lisp-indent-hook 1)
319
320 ;;; WHEN and UNLESS
321 ;;; These two forms are simplified ifs, with a single branch.
322
323 (defmacro when (condition &rest body)
324 "(when CONDITION . BODY) => evaluate BODY if CONDITION is true."
325 (list* 'if (list 'not condition) '() body))
326
327 (defmacro unless (condition &rest body)
328 "(unless CONDITION . BODY) => evaluate BODY if CONDITION is false."
329 (list* 'if condition '() body))
330 \f
331 ;;; CASE and ECASE
332 ;;; CASE selects among several clauses, based on the value (evaluated)
333 ;;; of a expression and a list of (unevaluated) key values. ECASE is
334 ;;; the same, but signals an error if no clause is activated.
335
336 (defmacro case (expr &rest cases)
337 "(case EXPR . CASES) => evals EXPR, chooses from CASES on that value.
338 EXPR -> any form
339 CASES -> list of clauses, non empty
340 CLAUSE -> HEAD . BODY
341 HEAD -> t = catch all, must be last clause
342 -> otherwise = same as t
343 -> nil = illegal
344 -> atom = activated if (eql EXPR HEAD)
345 -> list of atoms = activated if (memq EXPR HEAD)
346 BODY -> list of forms, implicit PROGN is built around it.
347 EXPR is evaluated only once."
348 (let* ((newsym (gentemp))
349 (clauses (case-clausify cases newsym)))
350 ;; convert case into a cond inside a let
351 (list 'let
352 (list (list newsym expr))
353 (list* 'cond (nreverse clauses)))))
354
355 (defmacro ecase (expr &rest cases)
356 "(ecase EXPR . CASES) => like `case', but error if no case fits.
357 `t'-clauses are not allowed."
358 (let* ((newsym (gentemp))
359 (clauses (case-clausify cases newsym)))
360 ;; check that no 't clause is present.
361 ;; case-clausify would put one such at the beginning of clauses
362 (if (eq (caar clauses) t)
363 (error "no clause-head should be `t' or `otherwise' for `ecase'"))
364 ;; insert error-catching clause
365 (setq clauses
366 (cons
367 (list 't (list 'error
368 "ecase on %s = %s failed to take any branch"
369 (list 'quote expr)
370 (list 'prin1-to-string newsym)))
371 clauses))
372 ;; generate code as usual
373 (list 'let
374 (list (list newsym expr))
375 (list* 'cond (nreverse clauses)))))
376
377 \f
378 (defun case-clausify (cases newsym)
379 "CASE-CLAUSIFY CASES NEWSYM => clauses for a 'cond'
380 Converts the CASES of a [e]case macro into cond clauses to be
381 evaluated inside a let that binds NEWSYM. Returns the clauses in
382 reverse order."
383 (do* ((currentpos cases (cdr currentpos))
384 (nextpos (cdr cases) (cdr nextpos))
385 (curclause (car cases) (car currentpos))
386 (result '()))
387 ((endp currentpos) result)
388 (let ((head (car curclause))
389 (body (cdr curclause)))
390 ;; construct a cond-clause according to the head
391 (cond ((null head)
392 (error "case clauses cannot have null heads: `%s'"
393 (prin1-to-string curclause)))
394 ((or (eq head 't)
395 (eq head 'otherwise))
396 ;; check it is the last clause
397 (if (not (endp nextpos))
398 (error "clause with `t' or `otherwise' head must be last"))
399 ;; accept this clause as a 't' for cond
400 (setq result (cons (cons 't body) result)))
401 ((atom head)
402 (setq result
403 (cons (cons (list 'eql newsym (list 'quote head)) body)
404 result)))
405 ((listp head)
406 (setq result
407 (cons (cons (list 'memq newsym (list 'quote head)) body)
408 result)))
409 (t
410 ;; catch-all for this parser
411 (error "don't know how to parse case clause `%s'"
412 (prin1-to-string head)))))))
413
414 ;;;; end of cl-conditionals.el
415 \f
416 ;;;; ITERATIONS
417 ;;;; This file provides simple iterative macros (a la Common Lisp)
418 ;;;; constructed on the basis of let, let* and while, which are the
419 ;;;; primitive binding/iteration constructs of Emacs Lisp
420 ;;;;
421 ;;;; The Common Lisp iterations use to have a block named nil
422 ;;;; wrapped around them, and allow declarations at the beginning
423 ;;;; of their bodies and you can return a value using (return ...).
424 ;;;; Nothing of the sort exists in Emacs Lisp, so I haven't tried
425 ;;;; to imitate these behaviors.
426 ;;;;
427 ;;;; Other than the above, the semantics of Common Lisp are
428 ;;;; correctly reproduced to the extent this was reasonable.
429 ;;;;
430 ;;;; Cesar Quiroz @ UofR DofCSc - Dec. 1986
431 ;;;; (quiroz@cs.rochester.edu)
432
433 ;;; some lisp-indentation information
434 (put 'do 'lisp-indent-hook 2)
435 (put 'do* 'lisp-indent-hook 2)
436 (put 'dolist 'lisp-indent-hook 1)
437 (put 'dotimes 'lisp-indent-hook 1)
438 (put 'do-symbols 'lisp-indent-hook 1)
439 (put 'do-all-symbols 'lisp-indent-hook 1)
440
441 \f
442 (defmacro do (stepforms endforms &rest body)
443 "(do STEPFORMS ENDFORMS . BODY): Iterate BODY, stepping some local variables.
444 STEPFORMS must be a list of symbols or lists. In the second case, the
445 lists must start with a symbol and contain up to two more forms. In
446 the STEPFORMS, a symbol is the same as a (symbol). The other 2 forms
447 are the initial value (def. NIL) and the form to step (def. itself).
448 The values used by initialization and stepping are computed in parallel.
449 The ENDFORMS are a list (CONDITION . ENDBODY). If the CONDITION
450 evaluates to true in any iteration, ENDBODY is evaluated and the last
451 form in it is returned.
452 The BODY (which may be empty) is evaluated at every iteration, with
453 the symbols of the STEPFORMS bound to the initial or stepped values."
454 ;; check the syntax of the macro
455 (and (check-do-stepforms stepforms)
456 (check-do-endforms endforms))
457 ;; construct emacs-lisp equivalent
458 (let ((initlist (extract-do-inits stepforms))
459 (steplist (extract-do-steps stepforms))
460 (endcond (car endforms))
461 (endbody (cdr endforms)))
462 (cons 'let (cons initlist
463 (cons (cons 'while (cons (list 'not endcond)
464 (append body steplist)))
465 (append endbody))))))
466
467 \f
468 (defmacro do* (stepforms endforms &rest body)
469 "`do*' is to `do' as `let*' is to `let'.
470 STEPFORMS must be a list of symbols or lists. In the second case, the
471 lists must start with a symbol and contain up to two more forms. In
472 the STEPFORMS, a symbol is the same as a (symbol). The other 2 forms
473 are the initial value (def. NIL) and the form to step (def. itself).
474 Initializations and steppings are done in the sequence they are written.
475 The ENDFORMS are a list (CONDITION . ENDBODY). If the CONDITION
476 evaluates to true in any iteration, ENDBODY is evaluated and the last
477 form in it is returned.
478 The BODY (which may be empty) is evaluated at every iteration, with
479 the symbols of the STEPFORMS bound to the initial or stepped values."
480 ;; check the syntax of the macro
481 (and (check-do-stepforms stepforms)
482 (check-do-endforms endforms))
483 ;; construct emacs-lisp equivalent
484 (let ((initlist (extract-do-inits stepforms))
485 (steplist (extract-do*-steps stepforms))
486 (endcond (car endforms))
487 (endbody (cdr endforms)))
488 (cons 'let* (cons initlist
489 (cons (cons 'while (cons (list 'not endcond)
490 (append body steplist)))
491 (append endbody))))))
492
493 \f
494 ;;; DO and DO* share the syntax checking functions that follow.
495
496 (defun check-do-stepforms (forms)
497 "True if FORMS is a valid stepforms for the do[*] macro (q.v.)"
498 (if (nlistp forms)
499 (error "init/step form for do[*] should be a list, not `%s'"
500 (prin1-to-string forms))
501 (mapcar
502 (function
503 (lambda (entry)
504 (if (not (or (symbolp entry)
505 (and (listp entry)
506 (symbolp (car entry))
507 (< (length entry) 4))))
508 (error "init/step must be %s, not `%s'"
509 "symbol or (symbol [init [step]])"
510 (prin1-to-string entry)))))
511 forms)))
512
513 (defun check-do-endforms (forms)
514 "True if FORMS is a valid endforms for the do[*] macro (q.v.)"
515 (if (nlistp forms)
516 (error "termination form for do macro should be a list, not `%s'"
517 (prin1-to-string forms))))
518
519 (defun extract-do-inits (forms)
520 "Returns a list of the initializations (for do) in FORMS
521 --a stepforms, see the do macro--. FORMS is assumed syntactically valid."
522 (mapcar
523 (function
524 (lambda (entry)
525 (cond ((symbolp entry)
526 (list entry nil))
527 ((listp entry)
528 (list (car entry) (cadr entry))))))
529 forms))
530
531 ;;; There used to be a reason to deal with DO differently than with
532 ;;; DO*. The writing of PSETQ has made it largely unnecessary.
533
534 (defun extract-do-steps (forms)
535 "EXTRACT-DO-STEPS FORMS => an s-expr
536 FORMS is the stepforms part of a DO macro (q.v.). This function
537 constructs an s-expression that does the stepping at the end of an
538 iteration."
539 (list (cons 'psetq (select-stepping-forms forms))))
540
541 (defun extract-do*-steps (forms)
542 "EXTRACT-DO*-STEPS FORMS => an s-expr
543 FORMS is the stepforms part of a DO* macro (q.v.). This function
544 constructs an s-expression that does the stepping at the end of an
545 iteration."
546 (list (cons 'setq (select-stepping-forms forms))))
547
548 (defun select-stepping-forms (forms)
549 "Separate only the forms that cause stepping."
550 (let ((result '()) ;ends up being (... var form ...)
551 (ptr forms) ;to traverse the forms
552 entry ;to explore each form in turn
553 )
554 (while ptr ;(not (endp entry)) might be safer
555 (setq entry (car ptr))
556 (cond ((and (listp entry) (= (length entry) 3))
557 (setq result (append ;append in reverse order!
558 (list (caddr entry) (car entry))
559 result))))
560 (setq ptr (cdr ptr))) ;step in the list of forms
561 (nreverse result)))
562 \f
563 ;;; Other iterative constructs
564
565 (defmacro dolist (stepform &rest body)
566 "(dolist (VAR LIST [RESULTFORM]) . BODY): do BODY for each elt of LIST.
567 The RESULTFORM defaults to nil. The VAR is bound to successive
568 elements of the value of LIST and remains bound (to the nil value) when the
569 RESULTFORM is evaluated."
570 ;; check sanity
571 (cond
572 ((nlistp stepform)
573 (error "stepform for `dolist' should be (VAR LIST [RESULT]), not `%s'"
574 (prin1-to-string stepform)))
575 ((not (symbolp (car stepform)))
576 (error "first component of stepform should be a symbol, not `%s'"
577 (prin1-to-string (car stepform))))
578 ((> (length stepform) 3)
579 (error "too many components in stepform `%s'"
580 (prin1-to-string stepform))))
581 ;; generate code
582 (let* ((var (car stepform))
583 (listform (cadr stepform))
584 (resultform (caddr stepform))
585 (listsym (gentemp)))
586 (nconc
587 (list 'let (list var (list listsym listform))
588 (nconc
589 (list 'while listsym
590 (list 'setq
591 var (list 'car listsym)
592 listsym (list 'cdr listsym)))
593 body))
594 (and resultform
595 (cons (list 'setq var nil)
596 (list resultform))))))
597
598 (defmacro dotimes (stepform &rest body)
599 "(dotimes (VAR COUNTFORM [RESULTFORM]) . BODY): Repeat BODY, counting in VAR.
600 The COUNTFORM should return a positive integer. The VAR is bound to
601 successive integers from 0 to COUNTFORM-1 and the BODY is repeated for
602 each of them. At the end, the RESULTFORM is evaluated and its value
603 returned. During this last evaluation, the VAR is still bound, and its
604 value is the number of times the iteration occurred. An omitted RESULTFORM
605 defaults to nil."
606 ;; check sanity
607 (cond
608 ((nlistp stepform)
609 (error "stepform for `dotimes' should be (VAR COUNT [RESULT]), not `%s'"
610 (prin1-to-string stepform)))
611 ((not (symbolp (car stepform)))
612 (error "first component of stepform should be a symbol, not `%s'"
613 (prin1-to-string (car stepform))))
614 ((> (length stepform) 3)
615 (error "too many components in stepform `%s'"
616 (prin1-to-string stepform))))
617 ;; generate code
618 (let* ((var (car stepform))
619 (countform (cadr stepform))
620 (resultform (caddr stepform))
621 (testsym (if (consp countform) (gentemp) countform)))
622 (nconc
623 (list
624 'let (cons (list var -1)
625 (and (not (eq countform testsym))
626 (list (list testsym countform))))
627 (nconc
628 (list 'while (list '< (list 'setq var (list '1+ var)) testsym))
629 body))
630 (and resultform (list resultform)))))
631 \f
632 (defmacro do-symbols (stepform &rest body)
633 "(do_symbols (VAR [OBARRAY [RESULTFORM]]) . BODY)
634 The VAR is bound to each of the symbols in OBARRAY (def. obarray) and
635 the BODY is repeatedly performed for each of those bindings. At the
636 end, RESULTFORM (def. nil) is evaluated and its value returned.
637 During this last evaluation, the VAR is still bound and its value is nil.
638 See also the function `mapatoms'."
639 ;; check sanity
640 (cond
641 ((nlistp stepform)
642 (error "stepform for `do-symbols' should be (VAR OBARRAY [RESULT]), not `%s'"
643 (prin1-to-string stepform)))
644 ((not (symbolp (car stepform)))
645 (error "first component of stepform should be a symbol, not `%s'"
646 (prin1-to-string (car stepform))))
647 ((> (length stepform) 3)
648 (error "too many components in stepform `%s'"
649 (prin1-to-string stepform))))
650 ;; generate code
651 (let* ((var (car stepform))
652 (oblist (cadr stepform))
653 (resultform (caddr stepform)))
654 (list 'progn
655 (list 'mapatoms
656 (list 'function
657 (cons 'lambda (cons (list var) body)))
658 oblist)
659 (list 'let
660 (list (list var nil))
661 resultform))))
662
663
664 (defmacro do-all-symbols (stepform &rest body)
665 "(do-all-symbols (VAR [RESULTFORM]) . BODY)
666 Is the same as (do-symbols (VAR obarray RESULTFORM) . BODY)."
667 (list*
668 'do-symbols
669 (list (car stepform) 'obarray (cadr stepform))
670 body))
671 \f
672 (defmacro loop (&rest body)
673 "(loop . BODY) repeats BODY indefinitely and does not return.
674 Normally BODY uses `throw' or `signal' to cause an exit.
675 The forms in BODY should be lists, as non-lists are reserved for new features."
676 ;; check that the body doesn't have atomic forms
677 (if (nlistp body)
678 (error "body of `loop' should be a list of lists or nil")
679 ;; ok, it is a list, check for atomic components
680 (mapcar
681 (function (lambda (component)
682 (if (nlistp component)
683 (error "components of `loop' should be lists"))))
684 body)
685 ;; build the infinite loop
686 (cons 'while (cons 't body))))
687
688 ;;;; end of cl-iterations.el
689 \f
690 ;;;; LISTS
691 ;;;; This file provides some of the lists machinery of Common-Lisp
692 ;;;; in a way compatible with Emacs Lisp. Especially, see the the
693 ;;;; typical c[ad]*r functions.
694 ;;;;
695 ;;;; Cesar Quiroz @ UofR DofCSc - Dec. 1986
696 ;;;; (quiroz@cs.rochester.edu)
697
698 ;;; Synonyms for list functions
699 (defsubst first (x)
700 "Synonym for `car'"
701 (car x))
702
703 (defsubst second (x)
704 "Return the second element of the list LIST."
705 (nth 1 x))
706
707 (defsubst third (x)
708 "Return the third element of the list LIST."
709 (nth 2 x))
710
711 (defsubst fourth (x)
712 "Return the fourth element of the list LIST."
713 (nth 3 x))
714
715 (defsubst fifth (x)
716 "Return the fifth element of the list LIST."
717 (nth 4 x))
718
719 (defsubst sixth (x)
720 "Return the sixth element of the list LIST."
721 (nth 5 x))
722
723 (defsubst seventh (x)
724 "Return the seventh element of the list LIST."
725 (nth 6 x))
726
727 (defsubst eighth (x)
728 "Return the eighth element of the list LIST."
729 (nth 7 x))
730
731 (defsubst ninth (x)
732 "Return the ninth element of the list LIST."
733 (nth 8 x))
734
735 (defsubst tenth (x)
736 "Return the tenth element of the list LIST."
737 (nth 9 x))
738
739 (defsubst rest (x)
740 "Synonym for `cdr'"
741 (cdr x))
742 \f
743 (defsubst endp (x)
744 "t if X is nil, nil if X is a cons; error otherwise."
745 (if (listp x)
746 (null x)
747 (error "endp received a non-cons, non-null argument `%s'"
748 (prin1-to-string x))))
749
750 (defun last (x)
751 "Returns the last link in the list LIST."
752 (if (nlistp x)
753 (error "arg to `last' must be a list"))
754 (do ((current-cons x (cdr current-cons))
755 (next-cons (cdr x) (cdr next-cons)))
756 ((endp next-cons) current-cons)))
757
758 (defun list-length (x) ;taken from CLtL sect. 15.2
759 "Returns the length of a non-circular list, or `nil' for a circular one."
760 (do ((n 0) ;counter
761 (fast x (cddr fast)) ;fast pointer, leaps by 2
762 (slow x (cdr slow)) ;slow pointer, leaps by 1
763 (ready nil)) ;indicates termination
764 (ready n)
765 (cond ((endp fast)
766 (setq ready t)) ;return n
767 ((endp (cdr fast))
768 (setq n (+ n 1))
769 (setq ready t)) ;return n+1
770 ((and (eq fast slow) (> n 0))
771 (setq n nil)
772 (setq ready t)) ;return nil
773 (t
774 (setq n (+ n 2)))))) ;just advance counter
775 \f
776 (defun butlast (list &optional n)
777 "Return a new list like LIST but sans the last N elements.
778 N defaults to 1. If the list doesn't have N elements, nil is returned."
779 (if (null n) (setq n 1))
780 (nreverse (nthcdr n (reverse list)))) ;optim. due to macrakis@osf.org
781
782 ;;; This version due to Aaron Larson (alarson@src.honeywell.com, 26 Jul 91)
783 (defun list* (arg &rest others)
784 "Return a new list containing the first arguments consed onto the last arg.
785 Thus, (list* 1 2 3 '(a b)) returns (1 2 3 a b)."
786 (if (null others)
787 arg
788 (let* ((others (cons arg (copy-sequence others)))
789 (a others))
790 (while (cdr (cdr a))
791 (setq a (cdr a)))
792 (setcdr a (car (cdr a)))
793 others)))
794
795 (defun adjoin (item list)
796 "Return a list which contains ITEM but is otherwise like LIST.
797 If ITEM occurs in LIST, the value is LIST. Otherwise it is (cons ITEM LIST).
798 When comparing ITEM against elements, `eql' is used."
799 (if (memq item list)
800 list
801 (cons item list)))
802
803 (defun ldiff (list sublist)
804 "Return a new list like LIST but sans SUBLIST.
805 SUBLIST must be one of the links in LIST; otherwise the value is LIST itself."
806 (do ((result '())
807 (curcons list (cdr curcons)))
808 ((or (endp curcons) (eq curcons sublist))
809 (reverse result))
810 (setq result (cons (car curcons) result))))
811 \f
812 ;;; The popular c[ad]*r functions and other list accessors.
813
814 ;;; To implement this efficiently, a new byte compile handler is used to
815 ;;; generate the minimal code, saving one function call.
816
817 (defsubst caar (X)
818 "Return the car of the car of X."
819 (car (car X)))
820
821 (defsubst cadr (X)
822 "Return the car of the cdr of X."
823 (car (cdr X)))
824
825 (defsubst cdar (X)
826 "Return the cdr of the car of X."
827 (cdr (car X)))
828
829 (defsubst cddr (X)
830 "Return the cdr of the cdr of X."
831 (cdr (cdr X)))
832
833 (defsubst caaar (X)
834 "Return the car of the car of the car of X."
835 (car (car (car X))))
836
837 (defsubst caadr (X)
838 "Return the car of the car of the cdr of X."
839 (car (car (cdr X))))
840
841 (defsubst cadar (X)
842 "Return the car of the cdr of the car of X."
843 (car (cdr (car X))))
844
845 (defsubst cdaar (X)
846 "Return the cdr of the car of the car of X."
847 (cdr (car (car X))))
848
849 (defsubst caddr (X)
850 "Return the car of the cdr of the cdr of X."
851 (car (cdr (cdr X))))
852
853 (defsubst cdadr (X)
854 "Return the cdr of the car of the cdr of X."
855 (cdr (car (cdr X))))
856
857 (defsubst cddar (X)
858 "Return the cdr of the cdr of the car of X."
859 (cdr (cdr (car X))))
860
861 (defsubst cdddr (X)
862 "Return the cdr of the cdr of the cdr of X."
863 (cdr (cdr (cdr X))))
864
865 (defsubst caaaar (X)
866 "Return the car of the car of the car of the car of X."
867 (car (car (car (car X)))))
868
869 (defsubst caaadr (X)
870 "Return the car of the car of the car of the cdr of X."
871 (car (car (car (cdr X)))))
872
873 (defsubst caadar (X)
874 "Return the car of the car of the cdr of the car of X."
875 (car (car (cdr (car X)))))
876
877 (defsubst cadaar (X)
878 "Return the car of the cdr of the car of the car of X."
879 (car (cdr (car (car X)))))
880
881 (defsubst cdaaar (X)
882 "Return the cdr of the car of the car of the car of X."
883 (cdr (car (car (car X)))))
884
885 (defsubst caaddr (X)
886 "Return the car of the car of the cdr of the cdr of X."
887 (car (car (cdr (cdr X)))))
888
889 (defsubst cadadr (X)
890 "Return the car of the cdr of the car of the cdr of X."
891 (car (cdr (car (cdr X)))))
892
893 (defsubst cdaadr (X)
894 "Return the cdr of the car of the car of the cdr of X."
895 (cdr (car (car (cdr X)))))
896
897 (defsubst caddar (X)
898 "Return the car of the cdr of the cdr of the car of X."
899 (car (cdr (cdr (car X)))))
900
901 (defsubst cdadar (X)
902 "Return the cdr of the car of the cdr of the car of X."
903 (cdr (car (cdr (car X)))))
904
905 (defsubst cddaar (X)
906 "Return the cdr of the cdr of the car of the car of X."
907 (cdr (cdr (car (car X)))))
908
909 (defsubst cadddr (X)
910 "Return the car of the cdr of the cdr of the cdr of X."
911 (car (cdr (cdr (cdr X)))))
912
913 (defsubst cddadr (X)
914 "Return the cdr of the cdr of the car of the cdr of X."
915 (cdr (cdr (car (cdr X)))))
916
917 (defsubst cdaddr (X)
918 "Return the cdr of the car of the cdr of the cdr of X."
919 (cdr (car (cdr (cdr X)))))
920
921 (defsubst cdddar (X)
922 "Return the cdr of the cdr of the cdr of the car of X."
923 (cdr (cdr (cdr (car X)))))
924
925 (defsubst cddddr (X)
926 "Return the cdr of the cdr of the cdr of the cdr of X."
927 (cdr (cdr (cdr (cdr X)))))
928 \f
929 ;;; some inverses of the accessors are needed for setf purposes
930
931 (defsubst setnth (n list newval)
932 "Set (nth N LIST) to NEWVAL. Returns NEWVAL."
933 (rplaca (nthcdr n list) newval))
934
935 (defun setnthcdr (n list newval)
936 "(setnthcdr N LIST NEWVAL) => NEWVAL
937 As a side effect, sets the Nth cdr of LIST to NEWVAL."
938 (when (< n 0)
939 (error "N must be 0 or greater, not %d" n))
940 (while (> n 0)
941 (setq list (cdr list)
942 n (- n 1)))
943 ;; here only if (zerop n)
944 (rplaca list (car newval))
945 (rplacd list (cdr newval))
946 newval)
947 \f
948 ;;; A-lists machinery
949
950 (defsubst acons (key item alist)
951 "Return a new alist with KEY paired with ITEM; otherwise like ALIST.
952 Does not copy ALIST."
953 (cons (cons key item) alist))
954
955 (defun pairlis (keys data &optional alist)
956 "Return a new alist with each elt of KEYS paired with an elt of DATA;
957 optional 3rd arg ALIST is nconc'd at the end. KEYS and DATA must
958 have the same length."
959 (unless (= (length keys) (length data))
960 (error "keys and data should be the same length"))
961 (do* ;;collect keys and data in front of alist
962 ((kptr keys (cdr kptr)) ;traverses the keys
963 (dptr data (cdr dptr)) ;traverses the data
964 (key (car kptr) (car kptr)) ;current key
965 (item (car dptr) (car dptr)) ;current data item
966 (result alist))
967 ((endp kptr) result)
968 (setq result (acons key item result))))
969
970 ;;;; end of cl-lists.el
971 \f
972 ;;;; SEQUENCES
973 ;;;; Emacs Lisp provides many of the 'sequences' functionality of
974 ;;;; Common Lisp. This file provides a few things that were left out.
975 ;;;;
976
977
978 (defkeyword :test "Used to designate positive (selection) tests.")
979 (defkeyword :test-not "Used to designate negative (rejection) tests.")
980 (defkeyword :key "Used to designate component extractions.")
981 (defkeyword :predicate "Used to define matching of sequence components.")
982 (defkeyword :start "Inclusive low index in sequence")
983 (defkeyword :end "Exclusive high index in sequence")
984 (defkeyword :start1 "Inclusive low index in first of two sequences.")
985 (defkeyword :start2 "Inclusive low index in second of two sequences.")
986 (defkeyword :end1 "Exclusive high index in first of two sequences.")
987 (defkeyword :end2 "Exclusive high index in second of two sequences.")
988 (defkeyword :count "Number of elements to affect.")
989 (defkeyword :from-end "T when counting backwards.")
990 (defkeyword :initial-value "For the syntax of #'reduce")
991 \f
992 (defun some (pred seq &rest moreseqs)
993 "Test PREDICATE on each element of SEQUENCE; is it ever non-nil?
994 Extra args are additional sequences; PREDICATE gets one arg from each
995 sequence and we advance down all the sequences together in lock-step.
996 A sequence means either a list or a vector."
997 (let ((args (reassemble-argslists (list* seq moreseqs))))
998 (do* ((ready nil) ;flag: return when t
999 (result nil) ;resulting value
1000 (applyval nil) ;result of applying pred once
1001 (remaining args
1002 (cdr remaining)) ;remaining argument sets
1003 (current (car remaining) ;current argument set
1004 (car remaining)))
1005 ((or ready (endp remaining)) result)
1006 (setq applyval (apply pred current))
1007 (when applyval
1008 (setq ready t)
1009 (setq result applyval)))))
1010
1011 (defun every (pred seq &rest moreseqs)
1012 "Test PREDICATE on each element of SEQUENCE; is it always non-nil?
1013 Extra args are additional sequences; PREDICATE gets one arg from each
1014 sequence and we advance down all the sequences together in lock-step.
1015 A sequence means either a list or a vector."
1016 (let ((args (reassemble-argslists (list* seq moreseqs))))
1017 (do* ((ready nil) ;flag: return when t
1018 (result t) ;resulting value
1019 (applyval nil) ;result of applying pred once
1020 (remaining args
1021 (cdr remaining)) ;remaining argument sets
1022 (current (car remaining) ;current argument set
1023 (car remaining)))
1024 ((or ready (endp remaining)) result)
1025 (setq applyval (apply pred current))
1026 (unless applyval
1027 (setq ready t)
1028 (setq result nil)))))
1029 \f
1030 (defun notany (pred seq &rest moreseqs)
1031 "Test PREDICATE on each element of SEQUENCE; is it always nil?
1032 Extra args are additional sequences; PREDICATE gets one arg from each
1033 sequence and we advance down all the sequences together in lock-step.
1034 A sequence means either a list or a vector."
1035 (let ((args (reassemble-argslists (list* seq moreseqs))))
1036 (do* ((ready nil) ;flag: return when t
1037 (result t) ;resulting value
1038 (applyval nil) ;result of applying pred once
1039 (remaining args
1040 (cdr remaining)) ;remaining argument sets
1041 (current (car remaining) ;current argument set
1042 (car remaining)))
1043 ((or ready (endp remaining)) result)
1044 (setq applyval (apply pred current))
1045 (when applyval
1046 (setq ready t)
1047 (setq result nil)))))
1048
1049 (defun notevery (pred seq &rest moreseqs)
1050 "Test PREDICATE on each element of SEQUENCE; is it sometimes nil?
1051 Extra args are additional sequences; PREDICATE gets one arg from each
1052 sequence and we advance down all the sequences together in lock-step.
1053 A sequence means either a list or a vector."
1054 (let ((args (reassemble-argslists (list* seq moreseqs))))
1055 (do* ((ready nil) ;flag: return when t
1056 (result nil) ;resulting value
1057 (applyval nil) ;result of applying pred once
1058 (remaining args
1059 (cdr remaining)) ;remaining argument sets
1060 (current (car remaining) ;current argument set
1061 (car remaining)))
1062 ((or ready (endp remaining)) result)
1063 (setq applyval (apply pred current))
1064 (unless applyval
1065 (setq ready t)
1066 (setq result t)))))
1067 \f
1068 ;;; More sequence functions that don't need keyword arguments
1069
1070 (defun concatenate (type &rest sequences)
1071 "(concatenate TYPE &rest SEQUENCES) => a sequence
1072 The sequence returned is of type TYPE (must be 'list, 'string, or 'vector) and
1073 contains the concatenation of the elements of all the arguments, in the order
1074 given."
1075 (let ((sequences (append sequences '(()))))
1076 (case type
1077 (list
1078 (apply (function append) sequences))
1079 (string
1080 (apply (function concat) sequences))
1081 (vector
1082 (apply (function vector) (apply (function append) sequences)))
1083 (t
1084 (error "type for concatenate `%s' not 'list, 'string or 'vector"
1085 (prin1-to-string type))))))
1086
1087 (defun map (type function &rest sequences)
1088 "(map TYPE FUNCTION &rest SEQUENCES) => a sequence
1089 The FUNCTION is called on each set of elements from the SEQUENCES \(stopping
1090 when the shortest sequence is terminated\) and the results are possibly
1091 returned in a sequence of type TYPE \(one of 'list, 'vector, 'string, or nil\)
1092 giving NIL for TYPE gets rid of the values."
1093 (if (not (memq type (list 'list 'string 'vector nil)))
1094 (error "type for map `%s' not 'list, 'string, 'vector or nil"
1095 (prin1-to-string type)))
1096 (let ((argslists (reassemble-argslists sequences))
1097 results)
1098 (if (null type)
1099 (while argslists ;don't bother accumulating
1100 (apply function (car argslists))
1101 (setq argslists (cdr argslists)))
1102 (setq results (mapcar (function (lambda (args) (apply function args)))
1103 argslists))
1104 (case type
1105 (list
1106 results)
1107 (string
1108 (funcall (function concat) results))
1109 (vector
1110 (apply (function vector) results))))))
1111 \f
1112 ;;; an inverse of elt is needed for setf purposes
1113
1114 (defun setelt (seq n newval)
1115 "In SEQUENCE, set the Nth element to NEWVAL. Returns NEWVAL.
1116 A sequence means either a list or a vector."
1117 (let ((l (length seq)))
1118 (if (or (< n 0) (>= n l))
1119 (error "N(%d) should be between 0 and %d" n l)
1120 ;; only two cases need be considered valid, as strings are arrays
1121 (cond ((listp seq)
1122 (setnth n seq newval))
1123 ((arrayp seq)
1124 (aset seq n newval))
1125 (t
1126 (error "SEQ should be a sequence, not `%s'"
1127 (prin1-to-string seq)))))))
1128 \f
1129 ;;; Testing with keyword arguments.
1130 ;;;
1131 ;;; Many of the sequence functions use keywords to denote some stylized
1132 ;;; form of selecting entries in a sequence. The involved arguments
1133 ;;; are collected with a &rest marker (as Emacs Lisp doesn't have a &key
1134 ;;; marker), then they are passed to build-klist, who
1135 ;;; constructs an association list. That association list is used to
1136 ;;; test for satisfaction and matching.
1137
1138 ;;; DON'T USE MEMBER, NOR ANY FUNCTION THAT COULD TAKE KEYWORDS HERE!!!
1139
1140 (defun build-klist (argslist acceptable &optional allow-other-keys)
1141 "Decode a keyword argument list ARGSLIST for keywords in ACCEPTABLE.
1142 ARGSLIST is a list, presumably the &rest argument of a call, whose
1143 even numbered elements must be keywords.
1144 ACCEPTABLE is a list of keywords, the only ones that are truly acceptable.
1145 The result is an alist containing the arguments named by the keywords
1146 in ACCEPTABLE, or an error is signalled, if something failed.
1147 If the third argument (an optional) is non-nil, other keys are acceptable."
1148 ;; check legality of the arguments, then destructure them
1149 (unless (and (listp argslist)
1150 (evenp (length argslist)))
1151 (error "build-klist: odd number of keyword-args"))
1152 (unless (and (listp acceptable)
1153 (every 'keywordp acceptable))
1154 (error "build-klist: second arg should be a list of keywords"))
1155 (multiple-value-bind
1156 (keywords forms)
1157 (unzip-list argslist)
1158 (unless (every 'keywordp keywords)
1159 (error "build-klist: expected keywords, found `%s'"
1160 (prin1-to-string keywords)))
1161 (unless (or allow-other-keys
1162 (every (function (lambda (keyword)
1163 (memq keyword acceptable)))
1164 keywords))
1165 (error "bad keyword[s]: %s not in %s"
1166 (prin1-to-string (mapcan (function (lambda (keyword)
1167 (if (memq keyword acceptable)
1168 nil
1169 (list keyword))))
1170 keywords))
1171 (prin1-to-string acceptable)))
1172 (do* ;;pick up the pieces
1173 ((auxlist ;auxiliary a-list, may
1174 (pairlis keywords forms)) ;contain repetitions and junk
1175 (ptr acceptable (cdr ptr)) ;pointer in acceptable
1176 (this (car ptr) (car ptr)) ;current acceptable keyword
1177 (auxval nil) ;used to move values around
1178 (alist '())) ;used to build the result
1179 ((endp ptr) alist)
1180 ;; if THIS appears in auxlist, use its value
1181 (when (setq auxval (assq this auxlist))
1182 (setq alist (cons auxval alist))))))
1183
1184
1185 (defun extract-from-klist (klist key &optional default)
1186 "(extract-from-klist KLIST KEY [DEFAULT]) => value of KEY or DEFAULT
1187 Extract value associated with KEY in KLIST (return DEFAULT if nil)."
1188 (let ((retrieved (cdr (assq key klist))))
1189 (or retrieved default)))
1190
1191 (defun keyword-argument-supplied-p (klist key)
1192 "(keyword-argument-supplied-p KLIST KEY) => nil or something
1193 NIL if KEY (a keyword) does not appear in the KLIST."
1194 (assq key klist))
1195
1196 (defun add-to-klist (key item klist)
1197 "(ADD-TO-KLIST KEY ITEM KLIST) => new KLIST
1198 Add association (KEY . ITEM) to KLIST."
1199 (setq klist (acons key item klist)))
1200
1201 (defun elt-satisfies-test-p (item elt klist)
1202 "(elt-satisfies-test-p ITEM ELT KLIST) => t or nil
1203 KLIST encodes a keyword-arguments test, as in CH. 14 of CLtL.
1204 True if the given ITEM and ELT satisfy the test."
1205 (let ((test (extract-from-klist klist :test))
1206 (test-not (extract-from-klist klist :test-not))
1207 (keyfn (extract-from-klist klist :key 'identity)))
1208 (cond (test
1209 (funcall test item (funcall keyfn elt)))
1210 (test-not
1211 (not (funcall test-not item (funcall keyfn elt))))
1212 (t ;should never happen
1213 (error "neither :test nor :test-not in `%s'"
1214 (prin1-to-string klist))))))
1215
1216 (defun elt-satisfies-if-p (item klist)
1217 "(elt-satisfies-if-p ITEM KLIST) => t or nil
1218 True if an -if style function was called and ITEM satisfies the
1219 predicate under :predicate in KLIST."
1220 (let ((predicate (extract-from-klist klist :predicate))
1221 (keyfn (extract-from-klist klist :key 'identity)))
1222 (funcall predicate (funcall keyfn item))))
1223
1224 (defun elt-satisfies-if-not-p (item klist)
1225 "(elt-satisfies-if-not-p ITEM KLIST) => t or nil
1226 KLIST encodes a keyword-arguments test, as in CH. 14 of CLtL.
1227 True if an -if-not style function was called and ITEM does not satisfy
1228 the predicate under :predicate in KLIST."
1229 (let ((predicate (extract-from-klist klist :predicate))
1230 (keyfn (extract-from-klist klist :key 'identity)))
1231 (not (funcall predicate (funcall keyfn item)))))
1232
1233 (defun elts-match-under-klist-p (e1 e2 klist)
1234 "(elts-match-under-klist-p E1 E2 KLIST) => t or nil
1235 KLIST encodes a keyword-arguments test, as in CH. 14 of CLtL.
1236 True if elements E1 and E2 match under the tests encoded in KLIST."
1237 (let ((test (extract-from-klist klist :test))
1238 (test-not (extract-from-klist klist :test-not))
1239 (keyfn (extract-from-klist klist :key 'identity)))
1240 (if (and test test-not)
1241 (error "both :test and :test-not in `%s'"
1242 (prin1-to-string klist)))
1243 (cond (test
1244 (funcall test (funcall keyfn e1) (funcall keyfn e2)))
1245 (test-not
1246 (not (funcall test-not (funcall keyfn e1) (funcall keyfn e2))))
1247 (t ;should never happen
1248 (error "neither :test nor :test-not in `%s'"
1249 (prin1-to-string klist))))))
1250 \f
1251 ;;; This macro simplifies using keyword args. It is less clumsy than using
1252 ;;; the primitives build-klist, etc... For instance, member could be written
1253 ;;; this way:
1254
1255 ;;; (defun member (item list &rest kargs)
1256 ;;; (with-keyword-args kargs (test test-not (key 'identity))
1257 ;;; ...))
1258
1259 ;;; Suggested by Robert Potter (potter@cs.rochester.edu, 15 Nov 1989)
1260
1261 (defmacro with-keyword-args (keyargslist vardefs &rest body)
1262 "(WITH-KEYWORD-ARGS KEYARGSLIST VARDEFS . BODY)
1263 KEYARGSLIST can be either a symbol or a list of one or two symbols.
1264 In the second case, the second symbol is either T or NIL, indicating whether
1265 keywords other than the mentioned ones are tolerable.
1266
1267 VARDEFS is a list. Each entry is either a VAR (symbol) or matches
1268 \(VAR [DEFAULT [KEYWORD]]). Just giving VAR is the same as giving
1269 \(VAR nil :VAR).
1270
1271 The BODY is executed in an environment where each VAR (a symbol) is bound to
1272 the value present in the KEYARGSLIST provided, or to the DEFAULT. The value
1273 is searched by using the keyword form of VAR (i.e., :VAR) or the optional
1274 keyword if provided.
1275
1276 Notice that this macro doesn't distinguish between a default value given
1277 explicitly by the user and one provided by default. See also the more
1278 primitive functions build-klist, add-to-klist, extract-from-klist,
1279 keyword-argument-supplied-p, elt-satisfies-test-p, elt-satisfies-if-p,
1280 elt-satisfies-if-not-p, elts-match-under-klist-p. They provide more complete,
1281 if clumsier, control over this feature."
1282 (let (allow-other-keys)
1283 (if (listp keyargslist)
1284 (if (> (length keyargslist) 2)
1285 (error
1286 "`%s' should be SYMBOL, (SYMBOL), or (SYMBOL t-OR-nil)"
1287 (prin1-to-string keyargslist))
1288 (setq allow-other-keys (cadr keyargslist)
1289 keyargslist (car keyargslist))
1290 (if (not (and
1291 (symbolp keyargslist)
1292 (memq allow-other-keys '(t nil))))
1293 (error
1294 "first subform should be SYMBOL, (SYMBOL), or (SYMBOL t-OR-nil)"
1295 )))
1296 (if (symbolp keyargslist)
1297 (setq allow-other-keys nil)
1298 (error
1299 "first subform should be SYMBOL, (SYMBOL), or (SYMBOL t-OR-nil)")))
1300 (let (vars defaults keywords forms
1301 (klistname (gensym "KLIST_")))
1302 (mapcar (function (lambda (entry)
1303 (if (symbolp entry) ;defaulty case
1304 (setq entry (list entry nil (keyword-of entry))))
1305 (let* ((l (length entry))
1306 (v (car entry))
1307 (d (cadr entry))
1308 (k (caddr entry)))
1309 (if (or (< l 1) (> l 3))
1310 (error
1311 "`%s' must match (VAR [DEFAULT [KEYWORD]])"
1312 (prin1-to-string entry)))
1313 (if (or (null v) (not (symbolp v)))
1314 (error
1315 "bad variable `%s': must be non-null symbol"
1316 (prin1-to-string v)))
1317 (setq vars (cons v vars))
1318 (setq defaults (cons d defaults))
1319 (if (< l 3)
1320 (setq k (keyword-of v)))
1321 (if (and (= l 3)
1322 (or (null k)
1323 (not (keywordp k))))
1324 (error
1325 "bad keyword `%s'" (prin1-to-string k)))
1326 (setq keywords (cons k keywords))
1327 (setq forms (cons (list v (list 'extract-from-klist
1328 klistname
1329 k
1330 d))
1331 forms)))))
1332 vardefs)
1333 (append
1334 (list 'let* (nconc (list (list klistname
1335 (list 'build-klist keyargslist
1336 (list 'quote keywords)
1337 allow-other-keys)))
1338 (nreverse forms)))
1339 body))))
1340 (put 'with-keyword-args 'lisp-indent-hook 1)
1341
1342 \f
1343 ;;; REDUCE
1344 ;;; It is here mostly as an example of how to use KLISTs.
1345 ;;;
1346 ;;; First of all, you need to declare the keywords (done elsewhere in this
1347 ;;; file):
1348 ;;; (defkeyword :from-end "syntax of sequence functions")
1349 ;;; (defkeyword :start "syntax of sequence functions")
1350 ;;; etc...
1351 ;;;
1352 ;;; Then, you capture all the possible keyword arguments with a &rest
1353 ;;; argument. You can pass that list downward again, of course, but
1354 ;;; internally you need to parse it into a KLIST (an alist, really). One uses
1355 ;;; (build-klist REST-ARGS ACCEPTABLE-KEYWORDS [ALLOW-OTHER]). You can then
1356 ;;; test for presence by using (keyword-argument-supplied-p KLIST KEY) and
1357 ;;; extract a value with (extract-from-klist KLIST KEY [DEFAULT]).
1358
1359 (defun reduce (function sequence &rest kargs)
1360 "Apply FUNCTION (a function of two arguments) to succesive pairs of elements
1361 from SEQUENCE. Some keyword arguments are valid after FUNCTION and SEQUENCE:
1362 :from-end If non-nil, process the values backwards
1363 :initial-value If given, prefix it to the SEQUENCE. Suffix, if :from-end
1364 :start Restrict reduction to the subsequence from this index
1365 :end Restrict reduction to the subsequence BEFORE this index.
1366 If the sequence is empty and no :initial-value is given, the FUNCTION is
1367 called on zero (not two) arguments. Otherwise, if there is exactly one
1368 element in the combination of SEQUENCE and the initial value, that element is
1369 returned."
1370 (let* ((klist (build-klist kargs '(:from-end :start :end :initial-value)))
1371 (length (length sequence))
1372 (from-end (extract-from-klist klist :from-end))
1373 (initial-value-given (keyword-argument-supplied-p
1374 klist :initial-value))
1375 (start (extract-from-klist kargs :start 0))
1376 (end (extract-from-klist kargs :end length)))
1377 (setq sequence (cl$subseq-as-list sequence start end))
1378 (if from-end
1379 (setq sequence (reverse sequence)))
1380 (if initial-value-given
1381 (setq sequence (cons (extract-from-klist klist :initial-value)
1382 sequence)))
1383 (if (null sequence)
1384 (funcall function) ;only use of 0 arguments
1385 (let* ((result (car sequence))
1386 (sequence (cdr sequence)))
1387 (while sequence
1388 (setq result (if from-end
1389 (funcall function (car sequence) result)
1390 (funcall function result (car sequence)))
1391 sequence (cdr sequence)))
1392 result))))
1393
1394 (defun cl$subseq-as-list (sequence start end)
1395 "(cl$subseq-as-list SEQUENCE START END) => a list"
1396 (let ((list (append sequence nil))
1397 (length (length sequence))
1398 result)
1399 (if (< start 0)
1400 (error "start should be >= 0, not %d" start))
1401 (if (> end length)
1402 (error "end should be <= %d, not %d" length end))
1403 (if (and (zerop start) (= end length))
1404 list
1405 (let ((i start)
1406 (vector (apply 'vector list)))
1407 (while (/= i end)
1408 (setq result (cons (elt vector i) result))
1409 (setq i (+ i 1)))
1410 (nreverse result)))))
1411
1412 ;;;; end of cl-sequences.el
1413 \f
1414 ;;;; Some functions with keyword arguments
1415 ;;;;
1416 ;;;; Both list and sequence functions are considered here together. This
1417 ;;;; doesn't fit any more with the original split of functions in files.
1418
1419 (defun member (item list &rest kargs)
1420 "Look for ITEM in LIST; return first tail of LIST the car of whose first
1421 cons cell tests the same as ITEM. Admits arguments :key, :test, and
1422 :test-not."
1423 (if (null kargs) ;treat this fast for efficiency
1424 (memq item list)
1425 (let* ((klist (build-klist kargs '(:test :test-not :key)))
1426 (test (extract-from-klist klist :test))
1427 (testnot (extract-from-klist klist :test-not))
1428 (key (extract-from-klist klist :key 'identity)))
1429 ;; another workaround allegedly for speed, BLAH
1430 (if (and (or (eq test 'eq) (eq test 'eql)
1431 (eq test (symbol-function 'eq))
1432 (eq test (symbol-function 'eql)))
1433 (null testnot)
1434 (or (eq key 'identity) ;either by default or so given
1435 (eq key (function identity)) ;could this happen?
1436 (eq key (symbol-function 'identity)) ;sheer paranoia
1437 ))
1438 (memq item list)
1439 (if (and test testnot)
1440 (error ":test and :test-not both specified for member"))
1441 (if (not (or test testnot))
1442 (setq test 'eql))
1443 ;; final hack: remove the indirection through the function names
1444 (if testnot
1445 (if (symbolp testnot)
1446 (setq testnot (symbol-function testnot)))
1447 (if (symbolp test)
1448 (setq test (symbol-function test))))
1449 (if (symbolp key)
1450 (setq key (symbol-function key)))
1451 ;; ok, go for it
1452 (let ((ptr list)
1453 (done nil)
1454 (result '()))
1455 (if testnot
1456 (while (not (or done (endp ptr)))
1457 (cond ((not (funcall testnot item (funcall key (car ptr))))
1458 (setq done t)
1459 (setq result ptr)))
1460 (setq ptr (cdr ptr)))
1461 (while (not (or done (endp ptr)))
1462 (cond ((funcall test item (funcall key (car ptr)))
1463 (setq done t)
1464 (setq result ptr)))
1465 (setq ptr (cdr ptr))))
1466 result)))))
1467 \f
1468 ;;;; MULTIPLE VALUES
1469 ;;;; This package approximates the behavior of the multiple-values
1470 ;;;; forms of Common Lisp.
1471 ;;;;
1472 ;;;; Cesar Quiroz @ UofR DofCSc - Dec. 1986
1473 ;;;; (quiroz@cs.rochester.edu)
1474
1475 ;;; Lisp indentation information
1476 (put 'multiple-value-bind 'lisp-indent-hook 2)
1477 (put 'multiple-value-setq 'lisp-indent-hook 2)
1478 (put 'multiple-value-list 'lisp-indent-hook nil)
1479 (put 'multiple-value-call 'lisp-indent-hook 1)
1480 (put 'multiple-value-prog1 'lisp-indent-hook 1)
1481
1482 ;;; Global state of the package is kept here
1483 (defvar *mvalues-values* nil
1484 "Most recently returned multiple-values")
1485 (defvar *mvalues-count* nil
1486 "Count of multiple-values returned, or nil if the mechanism was not used")
1487 \f
1488 ;;; values is the standard multiple-value-return form. Must be the
1489 ;;; last thing evaluated inside a function. If the caller is not
1490 ;;; expecting multiple values, only the first one is passed. (values)
1491 ;;; is the same as no-values returned (unaware callers see nil). The
1492 ;;; alternative (values-list <list>) is just a convenient shorthand
1493 ;;; and complements multiple-value-list.
1494
1495 (defun values (&rest val-forms)
1496 "Produce multiple values (zero or more). Each arg is one value.
1497 See also `multiple-value-bind', which is one way to examine the
1498 multiple values produced by a form. If the containing form or caller
1499 does not check specially to see multiple values, it will see only
1500 the first value."
1501 (setq *mvalues-values* val-forms)
1502 (setq *mvalues-count* (length *mvalues-values*))
1503 (car *mvalues-values*))
1504
1505 (defun values-list (&optional val-forms)
1506 "Produce multiple values (zero or more). Each element of LIST is one value.
1507 This is equivalent to (apply 'values LIST)."
1508 (cond ((nlistp val-forms)
1509 (error "Argument to values-list must be a list, not `%s'"
1510 (prin1-to-string val-forms))))
1511 (setq *mvalues-values* val-forms)
1512 (setq *mvalues-count* (length *mvalues-values*))
1513 (car *mvalues-values*))
1514 \f
1515 ;;; Callers that want to see the multiple values use these macros.
1516
1517 (defmacro multiple-value-list (form)
1518 "Execute FORM and return a list of all the (multiple) values FORM produces.
1519 See `values' and `multiple-value-bind'."
1520 (list 'progn
1521 (list 'setq '*mvalues-count* nil)
1522 (list 'let (list (list 'it '(gensym)))
1523 (list 'set 'it form)
1524 (list 'if '*mvalues-count*
1525 (list 'copy-sequence '*mvalues-values*)
1526 (list 'progn
1527 (list 'setq '*mvalues-count* 1)
1528 (list 'setq '*mvalues-values*
1529 (list 'list (list 'symbol-value 'it)))
1530 (list 'copy-sequence '*mvalues-values*))))))
1531
1532 (defmacro multiple-value-call (function &rest args)
1533 "Call FUNCTION on all the values produced by the remaining arguments.
1534 (multiple-value-call '+ (values 1 2) (values 3 4)) is 10."
1535 (let* ((result (gentemp))
1536 (arg (gentemp)))
1537 (list 'apply (list 'function (eval function))
1538 (list 'let* (list (list result '()))
1539 (list 'dolist (list arg (list 'quote args) result)
1540 (list 'setq result
1541 (list 'append
1542 result
1543 (list 'multiple-value-list
1544 (list 'eval arg)))))))))
1545
1546 (defmacro multiple-value-bind (vars form &rest body)
1547 "Bind VARS to the (multiple) values produced by FORM, then do BODY.
1548 VARS is a list of variables; each is bound to one of FORM's values.
1549 If FORM doesn't make enough values, the extra variables are bound to nil.
1550 (Ordinary forms produce only one value; to produce more, use `values'.)
1551 Extra values are ignored.
1552 BODY (zero or more forms) is executed with the variables bound,
1553 then the bindings are unwound."
1554 (let* ((vals (gentemp)) ;name for intermediate values
1555 (clauses (mv-bind-clausify ;convert into clauses usable
1556 vars vals))) ; in a let form
1557 (list* 'let*
1558 (cons (list vals (list 'multiple-value-list form))
1559 clauses)
1560 body)))
1561 \f
1562 (defmacro multiple-value-setq (vars form)
1563 "Set VARS to the (multiple) values produced by FORM.
1564 VARS is a list of variables; each is set to one of FORM's values.
1565 If FORM doesn't make enough values, the extra variables are set to nil.
1566 (Ordinary forms produce only one value; to produce more, use `values'.)
1567 Extra values are ignored."
1568 (let* ((vals (gentemp)) ;name for intermediate values
1569 (clauses (mv-bind-clausify ;convert into clauses usable
1570 vars vals))) ; in a setq (after append).
1571 (list 'let*
1572 (list (list vals (list 'multiple-value-list form)))
1573 (cons 'setq (apply (function append) clauses)))))
1574
1575 (defmacro multiple-value-prog1 (form &rest body)
1576 "Evaluate FORM, then BODY, then produce the same values FORM produced.
1577 Thus, (multiple-value-prog1 (values 1 2) (foobar)) produces values 1 and 2.
1578 This is like `prog1' except that `prog1' would produce only one value,
1579 which would be the first of FORM's values."
1580 (let* ((heldvalues (gentemp)))
1581 (cons 'let*
1582 (cons (list (list heldvalues (list 'multiple-value-list form)))
1583 (append body (list (list 'values-list heldvalues)))))))
1584
1585 ;;; utility functions
1586 ;;;
1587 ;;; mv-bind-clausify makes the pairs needed to have the variables in
1588 ;;; the variable list correspond with the values returned by the form.
1589 ;;; vals is a fresh symbol that intervenes in all the bindings.
1590
1591 (defun mv-bind-clausify (vars vals)
1592 "MV-BIND-CLAUSIFY VARS VALS => Auxiliary list
1593 Forms a list of pairs `(,(nth i vars) (nth i vals)) for i from 0 to
1594 the length of VARS (a list of symbols). VALS is just a fresh symbol."
1595 (if (or (nlistp vars)
1596 (notevery 'symbolp vars))
1597 (error "expected a list of symbols, not `%s'"
1598 (prin1-to-string vars)))
1599 (let* ((nvars (length vars))
1600 (clauses '()))
1601 (dotimes (n nvars clauses)
1602 (setq clauses (cons (list (nth n vars)
1603 (list 'nth n vals)) clauses)))))
1604
1605 ;;;; end of cl-multiple-values.el
1606 \f
1607 ;;;; ARITH
1608 ;;;; This file provides integer arithmetic extensions. Although
1609 ;;;; Emacs Lisp doesn't really support anything but integers, that
1610 ;;;; has still to be made to look more or less standard.
1611 ;;;;
1612 ;;;;
1613 ;;;; Cesar Quiroz @ UofR DofCSc - Dec. 1986
1614 ;;;; (quiroz@cs.rochester.edu)
1615
1616
1617 (defsubst plusp (number)
1618 "True if NUMBER is strictly greater than zero."
1619 (> number 0))
1620
1621 (defsubst minusp (number)
1622 "True if NUMBER is strictly less than zero."
1623 (< number 0))
1624
1625 (defsubst oddp (number)
1626 "True if INTEGER is not divisible by 2."
1627 (/= (% number 2) 0))
1628
1629 (defsubst evenp (number)
1630 "True if INTEGER is divisible by 2."
1631 (= (% number 2) 0))
1632
1633 (defsubst abs (number)
1634 "Return the absolute value of NUMBER."
1635 (if (< number 0)
1636 (- number)
1637 number))
1638
1639 (defsubst signum (number)
1640 "Return -1, 0 or 1 according to the sign of NUMBER."
1641 (cond ((< number 0)
1642 -1)
1643 ((> number 0)
1644 1)
1645 (t ;exactly zero
1646 0)))
1647 \f
1648 (defun gcd (&rest integers)
1649 "Return the greatest common divisor of all the arguments.
1650 The arguments must be integers. With no arguments, value is zero."
1651 (let ((howmany (length integers)))
1652 (cond ((= howmany 0)
1653 0)
1654 ((= howmany 1)
1655 (abs (car integers)))
1656 ((> howmany 2)
1657 (apply (function gcd)
1658 (cons (gcd (nth 0 integers) (nth 1 integers))
1659 (nthcdr 2 integers))))
1660 (t ;howmany=2
1661 ;; essentially the euclidean algorithm
1662 (when (zerop (* (nth 0 integers) (nth 1 integers)))
1663 (error "a zero argument is invalid for `gcd'"))
1664 (do* ((absa (abs (nth 0 integers))) ; better to operate only
1665 (absb (abs (nth 1 integers))) ;on positives.
1666 (dd (max absa absb)) ; setup correct order for the
1667 (ds (min absa absb)) ;succesive divisions.
1668 ;; intermediate results
1669 (q 0)
1670 (r 0)
1671 ;; final results
1672 (done nil) ; flag: end of iterations
1673 (result 0)) ; final value
1674 (done result)
1675 (setq q (/ dd ds))
1676 (setq r (% dd ds))
1677 (cond ((zerop r) (setq done t) (setq result ds))
1678 (t (setq dd ds) (setq ds r))))))))
1679
1680 (defun lcm (integer &rest more)
1681 "Return the least common multiple of all the arguments.
1682 The arguments must be integers and there must be at least one of them."
1683 (let ((howmany (length more))
1684 (a integer)
1685 (b (nth 0 more))
1686 prod ; intermediate product
1687 (yetmore (nthcdr 1 more)))
1688 (cond ((zerop howmany)
1689 (abs a))
1690 ((> howmany 1) ; recursive case
1691 (apply (function lcm)
1692 (cons (lcm a b) yetmore)))
1693 (t ; base case, just 2 args
1694 (setq prod (* a b))
1695 (cond
1696 ((zerop prod)
1697 0)
1698 (t
1699 (/ (abs prod) (gcd a b))))))))
1700 \f
1701 (defun isqrt (number)
1702 "Return the integer square root of NUMBER.
1703 NUMBER must not be negative. Result is largest integer less than or
1704 equal to the real square root of the argument."
1705 ;; The method used here is essentially the Newtonian iteration
1706 ;; x[n+1] <- (x[n] + Number/x[n]) / 2
1707 ;; suitably adapted to integer arithmetic.
1708 ;; Thanks to Philippe Schnoebelen <phs@lifia.imag.fr> for suggesting the
1709 ;; termination condition.
1710 (cond ((minusp number)
1711 (error "argument to `isqrt' (%d) must not be negative"
1712 number))
1713 ((zerop number)
1714 0)
1715 (t ;so (>= number 0)
1716 (do* ((approx 1) ;any positive integer will do
1717 (new 0) ;init value irrelevant
1718 (done nil))
1719 (done (if (> (* approx approx) number)
1720 (- approx 1)
1721 approx))
1722 (setq new (/ (+ approx (/ number approx)) 2)
1723 done (or (= new approx) (= new (+ approx 1)))
1724 approx new)))))
1725 \f
1726 (defun floor (number &optional divisor)
1727 "Divide DIVIDEND by DIVISOR, rounding toward minus infinity.
1728 DIVISOR defaults to 1. The remainder is produced as a second value."
1729 (cond ((and (null divisor) ; trivial case
1730 (numberp number))
1731 (values number 0))
1732 (t ; do the division
1733 (multiple-value-bind
1734 (q r s)
1735 (safe-idiv number divisor)
1736 (cond ((zerop s)
1737 (values 0 0))
1738 ((plusp s)
1739 (values q r))
1740 (t ;opposite-signs case
1741 (if (zerop r)
1742 (values (- q) 0)
1743 (let ((q (- (+ q 1))))
1744 (values q (- number (* q divisor)))))))))))
1745
1746 (defun ceiling (number &optional divisor)
1747 "Divide DIVIDEND by DIVISOR, rounding toward plus infinity.
1748 DIVISOR defaults to 1. The remainder is produced as a second value."
1749 (cond ((and (null divisor) ; trivial case
1750 (numberp number))
1751 (values number 0))
1752 (t ; do the division
1753 (multiple-value-bind
1754 (q r s)
1755 (safe-idiv number divisor)
1756 (cond ((zerop s)
1757 (values 0 0))
1758 ((plusp s)
1759 (values (+ q 1) (- r divisor)))
1760 (t
1761 (values (- q) (+ number (* q divisor)))))))))
1762 \f
1763 (defun truncate (number &optional divisor)
1764 "Divide DIVIDEND by DIVISOR, rounding toward zero.
1765 DIVISOR defaults to 1. The remainder is produced as a second value."
1766 (cond ((and (null divisor) ; trivial case
1767 (numberp number))
1768 (values number 0))
1769 (t ; do the division
1770 (multiple-value-bind
1771 (q r s)
1772 (safe-idiv number divisor)
1773 (cond ((zerop s)
1774 (values 0 0))
1775 ((plusp s) ;same as floor
1776 (values q r))
1777 (t ;same as ceiling
1778 (values (- q) (+ number (* q divisor)))))))))
1779
1780 (defun round (number &optional divisor)
1781 "Divide DIVIDEND by DIVISOR, rounding to nearest integer.
1782 DIVISOR defaults to 1. The remainder is produced as a second value."
1783 (cond ((and (null divisor) ; trivial case
1784 (numberp number))
1785 (values number 0))
1786 (t ; do the division
1787 (multiple-value-bind
1788 (q r s)
1789 (safe-idiv number divisor)
1790 (setq r (abs r))
1791 ;; adjust magnitudes first, and then signs
1792 (let ((other-r (- (abs divisor) r)))
1793 (cond ((> r other-r)
1794 (setq q (+ q 1)))
1795 ((and (= r other-r)
1796 (oddp q))
1797 ;; round to even is mandatory
1798 (setq q (+ q 1))))
1799 (setq q (* s q))
1800 (setq r (- number (* q divisor)))
1801 (values q r))))))
1802 \f
1803 ;;; These two functions access the implementation-dependent representation of
1804 ;;; the multiple value returns.
1805
1806 (defun mod (number divisor)
1807 "Return remainder of X by Y (rounding quotient toward minus infinity).
1808 That is, the remainder goes with the quotient produced by `floor'.
1809 Emacs Lisp hint:
1810 If you know that both arguments are positive, use `%' instead for speed."
1811 (floor number divisor)
1812 (cadr *mvalues-values*))
1813
1814 (defun rem (number divisor)
1815 "Return remainder of X by Y (rounding quotient toward zero).
1816 That is, the remainder goes with the quotient produced by `truncate'.
1817 Emacs Lisp hint:
1818 If you know that both arguments are positive, use `%' instead for speed."
1819 (truncate number divisor)
1820 (cadr *mvalues-values*))
1821 \f
1822 ;;; internal utilities
1823 ;;;
1824 ;;; safe-idiv performs an integer division with positive numbers only.
1825 ;;; It is known that some machines/compilers implement weird remainder
1826 ;;; computations when working with negatives, so the idea here is to
1827 ;;; make sure we know what is coming back to the caller in all cases.
1828
1829 ;;; Signum computation fixed by mad@math.keio.JUNET (MAEDA Atusi)
1830
1831 (defun safe-idiv (a b)
1832 "SAFE-IDIV A B => Q R S
1833 Q=|A|/|B|, S is the sign of A/B, R is the rest A - S*Q*B."
1834 ;; (unless (and (numberp a) (numberp b))
1835 ;; (error "arguments to `safe-idiv' must be numbers"))
1836 ;; (when (zerop b)
1837 ;; (error "cannot divide %d by zero" a))
1838 (let* ((q (/ (abs a) (abs b)))
1839 (s (* (signum a) (signum b)))
1840 (r (- a (* s q b))))
1841 (values q r s)))
1842
1843 ;;;; end of cl-arith.el
1844 \f
1845 ;;;; SETF
1846 ;;;; This file provides the setf macro and friends. The purpose has
1847 ;;;; been modest, only the simplest defsetf forms are accepted.
1848 ;;;; Use it and enjoy.
1849 ;;;;
1850 ;;;; Cesar Quiroz @ UofR DofCSc - Dec. 1986
1851 ;;;; (quiroz@cs.rochester.edu)
1852
1853
1854 (defkeyword :setf-update-fn
1855 "Property, its value is the function setf must invoke to update a
1856 generalized variable whose access form is a function call of the
1857 symbol that has this property.")
1858
1859 (defkeyword :setf-update-doc
1860 "Property of symbols that have a `defsetf' update function on them,
1861 installed by the `defsetf' from its optional third argument.")
1862 \f
1863 (defmacro setf (&rest pairs)
1864 "Generalized `setq' that can set things other than variable values.
1865 A use of `setf' looks like (setf {PLACE VALUE}...).
1866 The behavior of (setf PLACE VALUE) is to access the generalized variable
1867 at PLACE and store VALUE there. It returns VALUE. If there is more
1868 than one PLACE and VALUE, each PLACE is set from its VALUE before
1869 the next PLACE is evaluated."
1870 (let ((nforms (length pairs)))
1871 ;; check the number of subforms
1872 (cond ((/= (% nforms 2) 0)
1873 (error "odd number of arguments to `setf'"))
1874 ((= nforms 0)
1875 nil)
1876 ((> nforms 2)
1877 ;; this is the recursive case
1878 (cons 'progn
1879 (do* ;collect the place-value pairs
1880 ((args pairs (cddr args))
1881 (place (car args) (car args))
1882 (value (cadr args) (cadr args))
1883 (result '()))
1884 ((endp args) (nreverse result))
1885 (setq result
1886 (cons (list 'setf place value)
1887 result)))))
1888 (t ;i.e., nforms=2
1889 ;; this is the base case (SETF PLACE VALUE)
1890 (let* ((place (car pairs))
1891 (value (cadr pairs))
1892 (head nil)
1893 (updatefn nil))
1894 ;; dispatch on the type of the PLACE
1895 (cond ((symbolp place)
1896 (list 'setq place value))
1897 ((and (listp place)
1898 (setq head (car place))
1899 (symbolp head)
1900 (setq updatefn (get head :setf-update-fn)))
1901 ;; dispatch on the type of update function
1902 (cond ((and (consp updatefn) (eq (car updatefn) 'lambda))
1903 (cons 'funcall
1904 (cons (list 'function updatefn)
1905 (append (cdr place) (list value)))))
1906 ((and (symbolp updatefn)
1907 (fboundp updatefn)
1908 (let ((defn (symbol-function updatefn)))
1909 (or (subrp defn)
1910 (and (consp defn)
1911 (or (eq (car defn) 'lambda)
1912 (eq (car defn) 'macro))))))
1913 (cons updatefn (append (cdr place) (list value))))
1914 (t
1915 (multiple-value-bind
1916 (bindings newsyms)
1917 (pair-with-newsyms
1918 (append (cdr place) (list value)))
1919 ;; this let gets new symbols to ensure adequate
1920 ;; order of evaluation of the subforms.
1921 (list 'let
1922 bindings
1923 (cons updatefn newsyms))))))
1924 (t
1925 (error "no `setf' update-function for `%s'"
1926 (prin1-to-string place)))))))))
1927 \f
1928 (defmacro defsetf (accessfn updatefn &optional docstring)
1929 "Define how `setf' works on a certain kind of generalized variable.
1930 A use of `defsetf' looks like (defsetf ACCESSFN UPDATEFN [DOCSTRING]).
1931 ACCESSFN is a symbol. UPDATEFN is a function or macro which takes
1932 one more argument than ACCESSFN does. DEFSETF defines the translation
1933 of (SETF (ACCESFN . ARGS) NEWVAL) to be a form like (UPDATEFN ARGS... NEWVAL).
1934 The function UPDATEFN must return its last arg, after performing the
1935 updating called for."
1936 ;; reject ill-formed requests. too bad one can't test for functionp
1937 ;; or macrop.
1938 (when (not (symbolp accessfn))
1939 (error "first argument of `defsetf' must be a symbol, not `%s'"
1940 (prin1-to-string accessfn)))
1941 ;; update properties
1942 (list 'progn
1943 (list 'eval-and-compile
1944 (list 'put (list 'quote accessfn)
1945 :setf-update-fn (list 'function updatefn)))
1946 (list 'put (list 'quote accessfn) :setf-update-doc docstring)
1947 ;; any better thing to return?
1948 (list 'quote accessfn)))
1949 \f
1950 ;;; This section provides the "default" setfs for Common-Emacs-Lisp
1951 ;;; The user will not normally add anything to this, although
1952 ;;; defstruct will introduce new ones as a matter of fact.
1953 ;;;
1954 ;;; Apply is a special case. The Common Lisp
1955 ;;; standard makes the case of apply be useful when the user writes
1956 ;;; something like (apply #'name ...), Emacs Lisp doesn't have the #
1957 ;;; stuff, but it has (function ...). Notice that V18 includes a new
1958 ;;; apply: this file is compatible with V18 and pre-V18 Emacses.
1959
1960 ;;; INCOMPATIBILITY: the SETF macro evaluates its arguments in the
1961 ;;; (correct) left to right sequence *before* checking for apply
1962 ;;; methods (which should really be an special case inside setf). Due
1963 ;;; to this, the lambda expression defsetf'd to apply will succeed in
1964 ;;; applying the right function even if the name was not quoted, but
1965 ;;; computed! That extension is not Common Lisp (nor is particularly
1966 ;;; useful, I think).
1967
1968 (defsetf apply
1969 (lambda (&rest args)
1970 ;; dissasemble the calling form
1971 ;; "(((quote fn) x1 x2 ... xn) val)" (function instead of quote, too)
1972 (let* ((fnform (car args)) ;functional form
1973 (applyargs (append ;arguments "to apply fnform"
1974 (apply 'list* (butlast (cdr args)))
1975 (last args)))
1976 (newupdater nil)) ; its update-fn, if any
1977 (if (and (symbolp fnform)
1978 (setq newupdater (get fnform :setf-update-fn)))
1979 (apply newupdater applyargs)
1980 (error "can't `setf' to `%s'"
1981 (prin1-to-string fnform)))))
1982 "`apply' is a special case for `setf'")
1983
1984 \f
1985 (defsetf aref
1986 aset
1987 "`setf' inversion for `aref'")
1988
1989 (defsetf nth
1990 setnth
1991 "`setf' inversion for `nth'")
1992
1993 (defsetf nthcdr
1994 setnthcdr
1995 "`setf' inversion for `nthcdr'")
1996
1997 (defsetf elt
1998 setelt
1999 "`setf' inversion for `elt'")
2000
2001 (defsetf first
2002 (lambda (list val) (setnth 0 list val))
2003 "`setf' inversion for `first'")
2004
2005 (defsetf second
2006 (lambda (list val) (setnth 1 list val))
2007 "`setf' inversion for `second'")
2008
2009 (defsetf third
2010 (lambda (list val) (setnth 2 list val))
2011 "`setf' inversion for `third'")
2012
2013 (defsetf fourth
2014 (lambda (list val) (setnth 3 list val))
2015 "`setf' inversion for `fourth'")
2016
2017 (defsetf fifth
2018 (lambda (list val) (setnth 4 list val))
2019 "`setf' inversion for `fifth'")
2020
2021 (defsetf sixth
2022 (lambda (list val) (setnth 5 list val))
2023 "`setf' inversion for `sixth'")
2024
2025 (defsetf seventh
2026 (lambda (list val) (setnth 6 list val))
2027 "`setf' inversion for `seventh'")
2028 \f
2029 (defsetf eighth
2030 (lambda (list val) (setnth 7 list val))
2031 "`setf' inversion for `eighth'")
2032
2033 (defsetf ninth
2034 (lambda (list val) (setnth 8 list val))
2035 "`setf' inversion for `ninth'")
2036
2037 (defsetf tenth
2038 (lambda (list val) (setnth 9 list val))
2039 "`setf' inversion for `tenth'")
2040
2041 (defsetf rest
2042 (lambda (list val) (setcdr list val))
2043 "`setf' inversion for `rest'")
2044
2045 (defsetf car setcar "Replace the car of a cons")
2046
2047 (defsetf cdr setcdr "Replace the cdr of a cons")
2048
2049 (defsetf caar
2050 (lambda (list val) (setcar (nth 0 list) val))
2051 "`setf' inversion for `caar'")
2052
2053 (defsetf cadr
2054 (lambda (list val) (setcar (cdr list) val))
2055 "`setf' inversion for `cadr'")
2056
2057 (defsetf cdar
2058 (lambda (list val) (setcdr (car list) val))
2059 "`setf' inversion for `cdar'")
2060
2061 (defsetf cddr
2062 (lambda (list val) (setcdr (cdr list) val))
2063 "`setf' inversion for `cddr'")
2064
2065 (defsetf caaar
2066 (lambda (list val) (setcar (caar list) val))
2067 "`setf' inversion for `caaar'")
2068
2069 (defsetf caadr
2070 (lambda (list val) (setcar (cadr list) val))
2071 "`setf' inversion for `caadr'")
2072
2073 (defsetf cadar
2074 (lambda (list val) (setcar (cdar list) val))
2075 "`setf' inversion for `cadar'")
2076 \f
2077 (defsetf cdaar
2078 (lambda (list val) (setcdr (caar list) val))
2079 "`setf' inversion for `cdaar'")
2080
2081 (defsetf caddr
2082 (lambda (list val) (setcar (cddr list) val))
2083 "`setf' inversion for `caddr'")
2084
2085 (defsetf cdadr
2086 (lambda (list val) (setcdr (cadr list) val))
2087 "`setf' inversion for `cdadr'")
2088
2089 (defsetf cddar
2090 (lambda (list val) (setcdr (cdar list) val))
2091 "`setf' inversion for `cddar'")
2092
2093 (defsetf cdddr
2094 (lambda (list val) (setcdr (cddr list) val))
2095 "`setf' inversion for `cdddr'")
2096
2097 (defsetf caaaar
2098 (lambda (list val) (setcar (caaar list) val))
2099 "`setf' inversion for `caaaar'")
2100
2101 (defsetf caaadr
2102 (lambda (list val) (setcar (caadr list) val))
2103 "`setf' inversion for `caaadr'")
2104
2105 (defsetf caadar
2106 (lambda (list val) (setcar (cadar list) val))
2107 "`setf' inversion for `caadar'")
2108
2109 (defsetf cadaar
2110 (lambda (list val) (setcar (cdaar list) val))
2111 "`setf' inversion for `cadaar'")
2112
2113 (defsetf cdaaar
2114 (lambda (list val) (setcdr (caar list) val))
2115 "`setf' inversion for `cdaaar'")
2116
2117 (defsetf caaddr
2118 (lambda (list val) (setcar (caddr list) val))
2119 "`setf' inversion for `caaddr'")
2120 \f
2121 (defsetf cadadr
2122 (lambda (list val) (setcar (cdadr list) val))
2123 "`setf' inversion for `cadadr'")
2124
2125 (defsetf cdaadr
2126 (lambda (list val) (setcdr (caadr list) val))
2127 "`setf' inversion for `cdaadr'")
2128
2129 (defsetf caddar
2130 (lambda (list val) (setcar (cddar list) val))
2131 "`setf' inversion for `caddar'")
2132
2133 (defsetf cdadar
2134 (lambda (list val) (setcdr (cadar list) val))
2135 "`setf' inversion for `cdadar'")
2136
2137 (defsetf cddaar
2138 (lambda (list val) (setcdr (cdaar list) val))
2139 "`setf' inversion for `cddaar'")
2140
2141 (defsetf cadddr
2142 (lambda (list val) (setcar (cdddr list) val))
2143 "`setf' inversion for `cadddr'")
2144
2145 (defsetf cddadr
2146 (lambda (list val) (setcdr (cdadr list) val))
2147 "`setf' inversion for `cddadr'")
2148
2149 (defsetf cdaddr
2150 (lambda (list val) (setcdr (caddr list) val))
2151 "`setf' inversion for `cdaddr'")
2152
2153 (defsetf cdddar
2154 (lambda (list val) (setcdr (cddar list) val))
2155 "`setf' inversion for `cdddar'")
2156
2157 (defsetf cddddr
2158 (lambda (list val) (setcdr (cddr list) val))
2159 "`setf' inversion for `cddddr'")
2160
2161 (defsetf get put "`setf' inversion for `get' is `put'")
2162
2163 (defsetf symbol-function fset
2164 "`setf' inversion for `symbol-function' is `fset'")
2165
2166 (defsetf symbol-plist setplist
2167 "`setf' inversion for `symbol-plist' is `setplist'")
2168
2169 (defsetf symbol-value set
2170 "`setf' inversion for `symbol-value' is `set'")
2171
2172 (defsetf point goto-char
2173 "To set (point) to N, use (goto-char N)")
2174
2175 ;; how about defsetfing other Emacs forms?
2176 \f
2177 ;;; Modify macros
2178 ;;;
2179 ;;; It could be nice to implement define-modify-macro, but I don't
2180 ;;; think it really pays.
2181
2182 (defmacro incf (ref &optional delta)
2183 "(incf REF [DELTA]) -> increment the g.v. REF by DELTA (default 1)"
2184 (if (null delta)
2185 (setq delta 1))
2186 (list 'setf ref (list '+ ref delta)))
2187
2188 (defmacro decf (ref &optional delta)
2189 "(decf REF [DELTA]) -> decrement the g.v. REF by DELTA (default 1)"
2190 (if (null delta)
2191 (setq delta 1))
2192 (list 'setf ref (list '- ref delta)))
2193
2194 (defmacro push (item ref)
2195 "(push ITEM REF) -> cons ITEM at the head of the g.v. REF (a list)"
2196 (list 'setf ref (list 'cons item ref)))
2197
2198 (defmacro pushnew (item ref)
2199 "(pushnew ITEM REF): adjoin ITEM at the head of the g.v. REF (a list)"
2200 (list 'setf ref (list 'adjoin item ref)))
2201
2202 (defmacro pop (ref)
2203 "(pop REF) -> (prog1 (car REF) (setf REF (cdr REF)))"
2204 (let ((listname (gensym)))
2205 (list 'let (list (list listname ref))
2206 (list 'prog1
2207 (list 'car listname)
2208 (list 'setf ref (list 'cdr listname))))))
2209 \f
2210 ;;; PSETF
2211 ;;;
2212 ;;; Psetf is the generalized variable equivalent of psetq. The right
2213 ;;; hand sides are evaluated and assigned (via setf) to the left hand
2214 ;;; sides. The evaluations are done in an environment where they
2215 ;;; appear to occur in parallel.
2216
2217 (defmacro psetf (&rest body)
2218 "(psetf {var value }...) => nil
2219 Like setf, but all the values are computed before any assignment is made."
2220 (let ((length (length body)))
2221 (cond ((/= (% length 2) 0)
2222 (error "psetf needs an even number of arguments, %d given"
2223 length))
2224 ((null body)
2225 '())
2226 (t
2227 (list 'prog1 nil
2228 (let ((setfs '())
2229 (bodyforms (reverse body)))
2230 (while bodyforms
2231 (let* ((value (car bodyforms))
2232 (place (cadr bodyforms)))
2233 (setq bodyforms (cddr bodyforms))
2234 (if (null setfs)
2235 (setq setfs (list 'setf place value))
2236 (setq setfs (list 'setf place
2237 (list 'prog1 value
2238 setfs))))))
2239 setfs))))))
2240 \f
2241 ;;; SHIFTF and ROTATEF
2242 ;;;
2243
2244 (defmacro shiftf (&rest forms)
2245 "(shiftf PLACE1 PLACE2... NEWVALUE)
2246 Set PLACE1 to PLACE2, PLACE2 to PLACE3...
2247 Each PLACE is set to the old value of the following PLACE,
2248 and the last PLACE is set to the value NEWVALUE.
2249 Returns the old value of PLACE1."
2250 (unless (> (length forms) 1)
2251 (error "`shiftf' needs more than one argument"))
2252 (let ((places (butlast forms))
2253 (newvalue (car (last forms))))
2254 ;; the places are accessed to fresh symbols
2255 (multiple-value-bind
2256 (bindings newsyms)
2257 (pair-with-newsyms places)
2258 (list 'let bindings
2259 (cons 'setf
2260 (zip-lists places
2261 (append (cdr newsyms) (list newvalue))))
2262 (car newsyms)))))
2263
2264 (defmacro rotatef (&rest places)
2265 "(rotatef PLACE...) sets each PLACE to the old value of the following PLACE.
2266 The last PLACE is set to the old value of the first PLACE.
2267 Thus, the values rotate through the PLACEs. Returns nil."
2268 (if (null places)
2269 nil
2270 (multiple-value-bind
2271 (bindings newsyms)
2272 (pair-with-newsyms places)
2273 (list
2274 'let bindings
2275 (cons 'setf
2276 (zip-lists places
2277 (append (cdr newsyms) (list (car newsyms)))))
2278 nil))))
2279 \f
2280 ;;; GETF, REMF, and REMPROP
2281 ;;;
2282
2283 (defun getf (place indicator &optional default)
2284 "Return PLACE's PROPNAME property, or DEFAULT if not present."
2285 (while (and place (not (eq (car place) indicator)))
2286 (setq place (cdr (cdr place))))
2287 (if place
2288 (car (cdr place))
2289 default))
2290
2291 (defmacro getf$setf$method (place indicator default &rest newval)
2292 "SETF method for GETF. Not for public use."
2293 (case (length newval)
2294 (0 (setq newval default default nil))
2295 (1 (setq newval (car newval)))
2296 (t (error "Wrong number of arguments to (setf (getf ...)) form")))
2297 (let ((psym (gentemp)) (isym (gentemp)) (vsym (gentemp)))
2298 (list 'let (list (list psym place)
2299 (list isym indicator)
2300 (list vsym newval))
2301 (list 'while
2302 (list 'and psym
2303 (list 'not
2304 (list 'eq (list 'car psym) isym)))
2305 (list 'setq psym (list 'cdr (list 'cdr psym))))
2306 (list 'if psym
2307 (list 'setcar (list 'cdr psym) vsym)
2308 (list 'setf place
2309 (list 'nconc place (list 'list isym newval))))
2310 vsym)))
2311
2312 (defsetf getf
2313 getf$setf$method)
2314
2315 (defmacro remf (place indicator)
2316 "Remove from the property list at PLACE its PROPNAME property.
2317 Returns non-nil if and only if the property existed."
2318 (let ((psym (gentemp)) (isym (gentemp)))
2319 (list 'let (list (list psym place) (list isym indicator))
2320 (list 'cond
2321 (list (list 'eq isym (list 'car psym))
2322 (list 'setf place (list 'cdr (list 'cdr psym)))
2323 t)
2324 (list t
2325 (list 'setq psym (list 'cdr psym))
2326 (list 'while
2327 (list 'and (list 'cdr psym)
2328 (list 'not
2329 (list 'eq (list 'car (list 'cdr psym))
2330 isym)))
2331 (list 'setq psym (list 'cdr (list 'cdr psym))))
2332 (list 'cond
2333 (list (list 'cdr psym)
2334 (list 'setcdr psym
2335 (list 'cdr
2336 (list 'cdr (list 'cdr psym))))
2337 t)))))))
2338
2339 (defun remprop (symbol indicator)
2340 "Remove SYMBOL's PROPNAME property, returning non-nil if it was present."
2341 (remf (symbol-plist symbol) indicator))
2342
2343 \f
2344 ;;;; STRUCTS
2345 ;;;; This file provides the structures mechanism. See the
2346 ;;;; documentation for Common-Lisp's defstruct. Mine doesn't
2347 ;;;; implement all the functionality of the standard, although some
2348 ;;;; more could be grafted if so desired. More details along with
2349 ;;;; the code.
2350 ;;;;
2351 ;;;;
2352 ;;;; Cesar Quiroz @ UofR DofCSc - Dec. 1986
2353 ;;;; (quiroz@cs.rochester.edu)
2354
2355
2356 (defkeyword :include "Syntax of `defstruct'")
2357 (defkeyword :named "Syntax of `defstruct'")
2358 (defkeyword :conc-name "Syntax of `defstruct'")
2359 (defkeyword :copier "Syntax of `defstruct'")
2360 (defkeyword :predicate "Syntax of `defstruct'")
2361 (defkeyword :print-function "Syntax of `defstruct'")
2362 (defkeyword :type "Syntax of `defstruct'")
2363 (defkeyword :initial-offset "Syntax of `defstruct'")
2364
2365 (defkeyword :structure-doc "Documentation string for a structure.")
2366 (defkeyword :structure-slotsn "Number of slots in structure")
2367 (defkeyword :structure-slots "List of the slot's names")
2368 (defkeyword :structure-indices "List of (KEYWORD-NAME . INDEX)")
2369 (defkeyword :structure-initforms "List of (KEYWORD-NAME . INITFORM)")
2370 (defkeyword :structure-includes
2371 "() or list of a symbol, that this struct includes")
2372 (defkeyword :structure-included-in
2373 "List of the structs that include this")
2374
2375 \f
2376 (defmacro defstruct (&rest args)
2377 "(defstruct NAME [DOC-STRING] . SLOTS) define NAME as structure type.
2378 NAME must be a symbol, the name of the new structure. It could also
2379 be a list (NAME . OPTIONS).
2380
2381 Each option is either a symbol, or a list of a keyword symbol taken from the
2382 list \{:conc-name, :copier, :constructor, :predicate, :include,
2383 :print-function, :type, :initial-offset\}. The meanings of these are as in
2384 CLtL, except that no BOA-constructors are provided, and the options
2385 \{:print-fuction, :type, :initial-offset\} are ignored quietly. All these
2386 structs are named, in the sense that their names can be used for type
2387 discrimination.
2388
2389 The DOC-STRING is established as the `structure-doc' property of NAME.
2390
2391 The SLOTS are one or more of the following:
2392 SYMBOL -- meaning the SYMBOL is the name of a SLOT of NAME
2393 list of SYMBOL and VALUE -- meaning that VALUE is the initial value of
2394 the slot.
2395 `defstruct' defines functions `make-NAME', `NAME-p', `copy-NAME' for the
2396 structure, and functions with the same name as the slots to access
2397 them. `setf' of the accessors sets their values."
2398 (multiple-value-bind
2399 (name options docstring slotsn slots initlist)
2400 (parse$defstruct$args args)
2401 ;; Names for the member functions come from the options. The
2402 ;; slots* stuff collects info about the slots declared explicitly.
2403 (multiple-value-bind
2404 (conc-name constructor copier predicate
2405 moreslotsn moreslots moreinits included)
2406 (parse$defstruct$options name options slots)
2407 ;; The moreslots* stuff refers to slots gained as a consequence
2408 ;; of (:include clauses). -- Oct 89: Only one :include tolerated
2409 (when (and (numberp moreslotsn)
2410 (> moreslotsn 0))
2411 (setf slotsn (+ slotsn moreslotsn))
2412 (setf slots (append moreslots slots))
2413 (setf initlist (append moreinits initlist)))
2414 (unless (> slotsn 0)
2415 (error "%s needs at least one slot"
2416 (prin1-to-string name)))
2417 (let ((dups (duplicate-symbols-p slots)))
2418 (when dups
2419 (error "`%s' are duplicates"
2420 (prin1-to-string dups))))
2421 (setq initlist (simplify$inits slots initlist))
2422 (let (properties functions keywords accessors alterators returned)
2423 ;; compute properties of NAME
2424 (setq properties
2425 (append
2426 (list
2427 (list 'put (list 'quote name) :structure-doc
2428 docstring)
2429 (list 'put (list 'quote name) :structure-slotsn
2430 slotsn)
2431 (list 'put (list 'quote name) :structure-slots
2432 (list 'quote slots))
2433 (list 'put (list 'quote name) :structure-initforms
2434 (list 'quote initlist))
2435 (list 'put (list 'quote name) :structure-indices
2436 (list 'quote (extract$indices initlist))))
2437 ;; If this definition :includes another defstruct,
2438 ;; modify both property lists.
2439 (cond (included
2440 (list
2441 (list 'put
2442 (list 'quote name)
2443 :structure-includes
2444 (list 'quote included))
2445 (list 'pushnew
2446 (list 'quote name)
2447 (list 'get (list 'quote (car included))
2448 :structure-included-in))))
2449 (t
2450 (list
2451 (let ((old (gensym)))
2452 (list 'let
2453 (list (list old
2454 (list 'car
2455 (list 'get
2456 (list 'quote name)
2457 :structure-includes))))
2458 (list 'when old
2459 (list 'put
2460 old
2461 :structure-included-in
2462 (list 'delq
2463 (list 'quote name)
2464 ;; careful with destructive
2465 ;;manipulation!
2466 (list
2467 'append
2468 (list
2469 'get
2470 old
2471 :structure-included-in)
2472 '())
2473 )))))
2474 (list 'put
2475 (list 'quote name)
2476 :structure-includes
2477 '()))))
2478 ;; If this definition used to be :included in another, warn
2479 ;; that things make break. On the other hand, the redefinition
2480 ;; may be trivial, so don't call it an error.
2481 (let ((old (gensym)))
2482 (list
2483 (list 'let
2484 (list (list old (list 'get
2485 (list 'quote name)
2486 :structure-included-in)))
2487 (list 'when old
2488 (list 'message
2489 "`%s' redefined. Should redefine `%s'?"
2490 (list 'quote name)
2491 (list 'prin1-to-string old))))))))
2492
2493 ;; Compute functions associated with NAME. This is not
2494 ;; handling BOA constructors yet, but here would be the place.
2495 (setq functions
2496 (list
2497 (list 'fset (list 'quote constructor)
2498 (list 'function
2499 (list 'lambda (list '&rest 'args)
2500 (list 'make$structure$instance
2501 (list 'quote name)
2502 'args))))
2503 (list 'fset (list 'quote copier)
2504 (list 'function 'copy-sequence))
2505 (let ((typetag (gensym)))
2506 (list 'fset (list 'quote predicate)
2507 (list
2508 'function
2509 (list
2510 'lambda (list 'thing)
2511 (list 'and
2512 (list 'vectorp 'thing)
2513 (list 'let
2514 (list (list typetag
2515 (list 'elt 'thing 0)))
2516 (list 'or
2517 (list
2518 'and
2519 (list 'eq
2520 typetag
2521 (list 'quote name))
2522 (list '=
2523 (list 'length 'thing)
2524 (1+ slotsn)))
2525 (list
2526 'memq
2527 typetag
2528 (list 'get
2529 (list 'quote name)
2530 :structure-included-in))))))
2531 )))))
2532 ;; compute accessors for NAME's slots
2533 (multiple-value-setq
2534 (accessors alterators keywords)
2535 (build$accessors$for name conc-name predicate slots slotsn))
2536 ;; generate returned value -- not defined by the standard
2537 (setq returned
2538 (list
2539 (cons 'vector
2540 (mapcar
2541 (function (lambda (x) (list 'quote x)))
2542 (cons name slots)))))
2543 ;; generate code
2544 (cons 'progn
2545 (nconc properties functions keywords
2546 accessors alterators returned))))))
2547 \f
2548 (defun parse$defstruct$args (args)
2549 "(parse$defstruct$args ARGS) => NAME OPTIONS DOCSTRING SLOTSN SLOTS INITLIST
2550 NAME=symbol, OPTIONS=list of, DOCSTRING=string, SLOTSN=count of slots,
2551 SLOTS=list of their names, INITLIST=alist (keyword . initform)."
2552 (let (name ;args=(symbol...) or ((symbol...)...)
2553 options ;args=((symbol . options) ...)
2554 (docstring "") ;args=(head docstring . slotargs)
2555 slotargs ;second or third cdr of args
2556 (slotsn 0) ;number of slots
2557 (slots '()) ;list of slot names
2558 (initlist '())) ;list of (slot keyword . initform)
2559 ;; extract name and options
2560 (cond ((symbolp (car args)) ;simple name
2561 (setq name (car args)
2562 options '()))
2563 ((and (listp (car args)) ;(name . options)
2564 (symbolp (caar args)))
2565 (setq name (caar args)
2566 options (cdar args)))
2567 (t
2568 (error "first arg to `defstruct' must be symbol or (symbol ...)")))
2569 (setq slotargs (cdr args))
2570 ;; is there a docstring?
2571 (when (stringp (car slotargs))
2572 (setq docstring (car slotargs)
2573 slotargs (cdr slotargs)))
2574 ;; now for the slots
2575 (multiple-value-bind
2576 (slotsn slots initlist)
2577 (process$slots slotargs)
2578 (values name options docstring slotsn slots initlist))))
2579 \f
2580 (defun process$slots (slots)
2581 "(process$slots SLOTS) => SLOTSN SLOTSLIST INITLIST
2582 Converts a list of symbols or lists of symbol and form into the last 3
2583 values returned by PARSE$DEFSTRUCT$ARGS."
2584 (let ((slotsn (length slots)) ;number of slots
2585 slotslist ;(slot1 slot2 ...)
2586 initlist) ;((:slot1 . init1) ...)
2587 (do*
2588 ((ptr slots (cdr ptr))
2589 (this (car ptr) (car ptr)))
2590 ((endp ptr))
2591 (cond ((symbolp this)
2592 (setq slotslist (cons this slotslist))
2593 (setq initlist (acons (keyword-of this) nil initlist)))
2594 ((and (listp this)
2595 (symbolp (car this)))
2596 (let ((name (car this))
2597 (form (cadr this)))
2598 ;; this silently ignores any slot options. bad...
2599 (setq slotslist (cons name slotslist))
2600 (setq initlist (acons (keyword-of name) form initlist))))
2601 (t
2602 (error "slot should be symbol or (symbol ...), not `%s'"
2603 (prin1-to-string this)))))
2604 (values slotsn (nreverse slotslist) (nreverse initlist))))
2605 \f
2606 (defun parse$defstruct$options (name options slots)
2607 "(parse$defstruct$options name OPTIONS SLOTS) => many values
2608 A defstruct named NAME, with options list OPTIONS, has already slots SLOTS.
2609 Parse the OPTIONS and return the updated form of the struct's slots and other
2610 information. The values returned are:
2611
2612 CONC-NAME is the string to use as prefix/suffix in the methods,
2613 CONST is the name of the official constructor,
2614 COPIER is the name of the structure copier,
2615 PRED is the name of the type predicate,
2616 MORESLOTSN is the number of slots added by :include,
2617 MORESLOTS is the list of slots added by :include,
2618 MOREINITS is the list of initialization forms added by :include,
2619 INCLUDED is nil, or the list of the symbol added by :include"
2620 (let* ((namestring (symbol-name name))
2621 ;; to build the return values
2622 (conc-name (concat namestring "-"))
2623 (const (intern (concat "make-" namestring)))
2624 (copier (intern (concat "copy-" namestring)))
2625 (pred (intern (concat namestring "-p")))
2626 (moreslotsn 0)
2627 (moreslots '())
2628 (moreinits '())
2629 ;; auxiliaries
2630 option-head ;When an option is not a plain
2631 option-second ; keyword, it must be a list of
2632 option-rest ; the form (head second . rest)
2633 these-slotsn ;When :include is found, the
2634 these-slots ; info about the included
2635 these-inits ; structure is added here.
2636 included ;NIL or (list INCLUDED)
2637 )
2638 ;; Values above are the defaults. Now we read the options themselves
2639 (dolist (option options)
2640 ;; 2 cases arise, as options must be a keyword or a list
2641 (cond
2642 ((keywordp option)
2643 (case option
2644 (:named
2645 ) ;ignore silently
2646 (t
2647 (error "can't recognize option `%s'"
2648 (prin1-to-string option)))))
2649 ((and (listp option)
2650 (keywordp (setq option-head (car option))))
2651 (setq option-second (second option))
2652 (setq option-rest (nthcdr 2 option))
2653 (case option-head
2654 (:conc-name
2655 (setq conc-name
2656 (cond
2657 ((stringp option-second)
2658 option-second)
2659 ((null option-second)
2660 "")
2661 (t
2662 (error "`%s' is invalid as `conc-name'"
2663 (prin1-to-string option-second))))))
2664 (:copier
2665 (setq copier
2666 (cond
2667 ((and (symbolp option-second)
2668 (null option-rest))
2669 option-second)
2670 (t
2671 (error "can't recognize option `%s'"
2672 (prin1-to-string option))))))
2673 \f
2674 (:constructor ;no BOA-constructors allowed
2675 (setq const
2676 (cond
2677 ((and (symbolp option-second)
2678 (null option-rest))
2679 option-second)
2680 (t
2681 (error "can't recognize option `%s'"
2682 (prin1-to-string option))))))
2683 (:predicate
2684 (setq pred
2685 (cond
2686 ((and (symbolp option-second)
2687 (null option-rest))
2688 option-second)
2689 (t
2690 (error "can't recognize option `%s'"
2691 (prin1-to-string option))))))
2692 (:include
2693 (unless (symbolp option-second)
2694 (error "arg to `:include' should be a symbol, not `%s'"
2695 (prin1-to-string option-second)))
2696 (setq these-slotsn (get option-second :structure-slotsn)
2697 these-slots (get option-second :structure-slots)
2698 these-inits (get option-second :structure-initforms))
2699 (unless (and (numberp these-slotsn)
2700 (> these-slotsn 0))
2701 (error "`%s' is not a valid structure"
2702 (prin1-to-string option-second)))
2703 (if included
2704 (error "`%s' already includes `%s', can't include `%s' too"
2705 name (car included) option-second)
2706 (push option-second included))
2707 (multiple-value-bind
2708 (xtra-slotsn xtra-slots xtra-inits)
2709 (process$slots option-rest)
2710 (when (> xtra-slotsn 0)
2711 (dolist (xslot xtra-slots)
2712 (unless (memq xslot these-slots)
2713 (error "`%s' is not a slot of `%s'"
2714 (prin1-to-string xslot)
2715 (prin1-to-string option-second))))
2716 (setq these-inits (append xtra-inits these-inits)))
2717 (setq moreslotsn (+ moreslotsn these-slotsn))
2718 (setq moreslots (append these-slots moreslots))
2719 (setq moreinits (append these-inits moreinits))))
2720 ((:print-function :type :initial-offset)
2721 ) ;ignore silently
2722 (t
2723 (error "can't recognize option `%s'"
2724 (prin1-to-string option)))))
2725 (t
2726 (error "can't recognize option `%s'"
2727 (prin1-to-string option)))))
2728 ;; Return values found
2729 (values conc-name const copier pred
2730 moreslotsn moreslots moreinits
2731 included)))
2732 \f
2733 (defun simplify$inits (slots initlist)
2734 "(simplify$inits SLOTS INITLIST) => new INITLIST
2735 Removes from INITLIST - an ALIST - any shadowed bindings."
2736 (let ((result '()) ;built here
2737 key ;from the slot
2738 )
2739 (dolist (slot slots)
2740 (setq key (keyword-of slot))
2741 (setq result (acons key (cdr (assoc key initlist)) result)))
2742 (nreverse result)))
2743
2744 (defun extract$indices (initlist)
2745 "(extract$indices INITLIST) => indices list
2746 Kludge. From a list of pairs (keyword . form) build a list of pairs
2747 of the form (keyword . position in list from 0). Useful to precompute
2748 some of the work of MAKE$STRUCTURE$INSTANCE."
2749 (let ((result '())
2750 (index 0))
2751 (dolist (entry initlist (nreverse result))
2752 (setq result (acons (car entry) index result)
2753 index (+ index 1)))))
2754 \f
2755 (defun build$accessors$for (name conc-name predicate slots slotsn)
2756 "(build$accessors$for NAME PREDICATE SLOTS SLOTSN) => FSETS DEFSETFS KWDS
2757 Generate the code for accesors and defsetfs of a structure called
2758 NAME, whose slots are SLOTS. Also, establishes the keywords for the
2759 slots names."
2760 (do ((i 0 (1+ i))
2761 (accessors '())
2762 (alterators '())
2763 (keywords '())
2764 (canonic "")) ;slot name with conc-name prepended
2765 ((>= i slotsn)
2766 (values
2767 (nreverse accessors) (nreverse alterators) (nreverse keywords)))
2768 (setq canonic (intern (concat conc-name (symbol-name (nth i slots)))))
2769 (setq accessors
2770 (cons
2771 (list 'fset (list 'quote canonic)
2772 (list 'function
2773 (list 'lambda (list 'object)
2774 (list 'cond
2775 (list (list predicate 'object)
2776 (list 'aref 'object (1+ i)))
2777 (list 't
2778 (list 'error
2779 "`%s' is not a struct %s"
2780 (list 'prin1-to-string
2781 'object)
2782 (list 'prin1-to-string
2783 (list 'quote
2784 name))))))))
2785 accessors))
2786 (setq alterators
2787 (cons
2788 (list 'defsetf canonic
2789 (list 'lambda (list 'object 'newval)
2790 (list 'cond
2791 (list (list predicate 'object)
2792 (list 'aset 'object (1+ i) 'newval))
2793 (list 't
2794 (list 'error
2795 "`%s' not a `%s'"
2796 (list 'prin1-to-string
2797 'object)
2798 (list 'prin1-to-string
2799 (list 'quote
2800 name)))))))
2801 alterators))
2802 (setq keywords
2803 (cons (list 'defkeyword (keyword-of (nth i slots)))
2804 keywords))))
2805 \f
2806 (defun make$structure$instance (name args)
2807 "(make$structure$instance NAME ARGS) => new struct NAME
2808 A struct of type NAME is created, some slots might be initialized
2809 according to ARGS (the &rest argument of MAKE-name)."
2810 (unless (symbolp name)
2811 (error "`%s' is not a possible name for a structure"
2812 (prin1-to-string name)))
2813 (let ((initforms (get name :structure-initforms))
2814 (slotsn (get name :structure-slotsn))
2815 (indices (get name :structure-indices))
2816 initalist ;pairlis'd on initforms
2817 initializers ;definitive initializers
2818 )
2819 ;; check sanity of the request
2820 (unless (and (numberp slotsn)
2821 (> slotsn 0))
2822 (error "`%s' is not a defined structure"
2823 (prin1-to-string name)))
2824 (unless (evenp (length args))
2825 (error "slot initializers `%s' not of even length"
2826 (prin1-to-string args)))
2827 ;; analyze the initializers provided by the call
2828 (multiple-value-bind
2829 (speckwds specvals) ;keywords and values given
2830 (unzip-list args) ; by the user
2831 ;; check that all the arguments are introduced by keywords
2832 (unless (every (function keywordp) speckwds)
2833 (error "all of the names in `%s' should be keywords"
2834 (prin1-to-string speckwds)))
2835 ;; check that all the keywords are known
2836 (dolist (kwd speckwds)
2837 (unless (numberp (cdr (assoc kwd indices)))
2838 (error "`%s' is not a valid slot name for %s"
2839 (prin1-to-string kwd) (prin1-to-string name))))
2840 ;; update initforms
2841 (setq initalist
2842 (pairlis speckwds
2843 (do* ;;protect values from further evaluation
2844 ((ptr specvals (cdr ptr))
2845 (val (car ptr) (car ptr))
2846 (result '()))
2847 ((endp ptr) (nreverse result))
2848 (setq result
2849 (cons (list 'quote val)
2850 result)))
2851 (copy-sequence initforms)))
2852 ;; compute definitive initializers
2853 (setq initializers
2854 (do* ;;gather the values of the most definitive forms
2855 ((ptr indices (cdr ptr))
2856 (key (caar ptr) (caar ptr))
2857 (result '()))
2858 ((endp ptr) (nreverse result))
2859 (setq result
2860 (cons (eval (cdr (assoc key initalist))) result))))
2861 ;; do real initialization
2862 (apply (function vector)
2863 (cons name initializers)))))
2864
2865 ;;;; end of cl-structs.el
2866 \f
2867 ;;; For lisp-interaction mode, so that multiple values can be seen when passed
2868 ;;; back. Lies every now and then...
2869
2870 (defvar - nil "form currently under evaluation")
2871 (defvar + nil "previous -")
2872 (defvar ++ nil "previous +")
2873 (defvar +++ nil "previous ++")
2874 (defvar / nil "list of values returned by +")
2875 (defvar // nil "list of values returned by ++")
2876 (defvar /// nil "list of values returned by +++")
2877 (defvar * nil "(first) value of +")
2878 (defvar ** nil "(first) value of ++")
2879 (defvar *** nil "(first) value of +++")
2880
2881 (defun cl-eval-print-last-sexp ()
2882 "Evaluate sexp before point; print value\(s\) into current buffer.
2883 If the evaled form returns multiple values, they are shown one to a line.
2884 The variables -, +, ++, +++, *, **, ***, /, //, /// have their usual meaning.
2885
2886 It clears the multiple-value passing mechanism, and does not pass back
2887 multiple values. Use this only if you are debugging cl.el and understand well
2888 how the multiple-value stuff works, because it can be fooled into believing
2889 that multiple values have been returned when they actually haven't, for
2890 instance
2891 \(identity \(values nil 1\)\)
2892 However, even when this fails, you can trust the first printed value to be
2893 \(one of\) the returned value\(s\)."
2894 (interactive)
2895 ;; top level call, can reset mvalues
2896 (setq *mvalues-count* nil
2897 *mvalues-values* nil)
2898 (setq - (car (read-from-string
2899 (buffer-substring
2900 (let ((stab (syntax-table)))
2901 (unwind-protect
2902 (save-excursion
2903 (set-syntax-table emacs-lisp-mode-syntax-table)
2904 (forward-sexp -1)
2905 (point))
2906 (set-syntax-table stab)))
2907 (point)))))
2908 (setq *** **
2909 ** *
2910 * (eval -))
2911 (setq /// //
2912 // /
2913 / *mvalues-values*)
2914 (setq +++ ++
2915 ++ +
2916 + -)
2917 (cond ((or (null *mvalues-count*) ;mvalues mechanism not used
2918 (not (eq * (car *mvalues-values*))))
2919 (print * (current-buffer)))
2920 ((null /) ;no values returned
2921 (terpri (current-buffer)))
2922 (t ;more than zero mvalues
2923 (terpri (current-buffer))
2924 (mapcar (function (lambda (value)
2925 (prin1 value (current-buffer))
2926 (terpri (current-buffer))))
2927 /)))
2928 (setq *mvalues-count* nil ;make sure
2929 *mvalues-values* nil))
2930 \f
2931 ;;;; More LISTS functions
2932 ;;;;
2933
2934 ;;; Some mapping functions on lists, commonly useful.
2935 ;;; They take no extra sequences, to go along with Emacs Lisp's MAPCAR.
2936
2937 (defun mapc (function list)
2938 "(MAPC FUNCTION LIST) => LIST
2939 Apply FUNCTION to each element of LIST, return LIST.
2940 Like mapcar, but called only for effect."
2941 (let ((args list))
2942 (while args
2943 (funcall function (car args))
2944 (setq args (cdr args))))
2945 list)
2946
2947 (defun maplist (function list)
2948 "(MAPLIST FUNCTION LIST) => list'ed results of FUNCTION on cdrs of LIST
2949 Apply FUNCTION to successive sublists of LIST, return the list of the results"
2950 (let ((args list)
2951 results '())
2952 (while args
2953 (setq results (cons (funcall function args) results)
2954 args (cdr args)))
2955 (nreverse results)))
2956
2957 (defun mapl (function list)
2958 "(MAPL FUNCTION LIST) => LIST
2959 Apply FUNCTION to successive cdrs of LIST, return LIST.
2960 Like maplist, but called only for effect."
2961 (let ((args list))
2962 (while args
2963 (funcall function args)
2964 (setq args (cdr args)))
2965 list))
2966
2967 (defun mapcan (function list)
2968 "(MAPCAN FUNCTION LIST) => nconc'd results of FUNCTION on LIST
2969 Apply FUNCTION to each element of LIST, nconc the results.
2970 Beware: nconc destroys its first argument! See copy-list."
2971 (let ((args list)
2972 (results '()))
2973 (while args
2974 (setq results (nconc (funcall function (car args)) results)
2975 args (cdr args)))
2976 (nreverse results)))
2977
2978 (defun mapcon (function list)
2979 "(MAPCON FUNCTION LIST) => nconc'd results of FUNCTION on cdrs of LIST
2980 Apply FUNCTION to successive sublists of LIST, nconc the results.
2981 Beware: nconc destroys its first argument! See copy-list."
2982 (let ((args list)
2983 (results '()))
2984 (while args
2985 (setq results (nconc (funcall function args) results)
2986 args (cdr args)))
2987 (nreverse results)))
2988
2989 ;;; Copiers
2990
2991 (defsubst copy-list (list)
2992 "Build a copy of LIST"
2993 (append list '()))
2994
2995 (defun copy-tree (tree)
2996 "Build a copy of the tree of conses TREE
2997 The argument is a tree of conses, it is recursively copied down to
2998 non conses. Circularity and sharing of substructure are not
2999 necessarily preserved."
3000 (if (consp tree)
3001 (cons (copy-tree (car tree))
3002 (copy-tree (cdr tree)))
3003 tree))
3004
3005 ;;; reversals, and destructive manipulations of a list's spine
3006
3007 (defun revappend (x y)
3008 "does what (append (reverse X) Y) would, only faster"
3009 (if (endp x)
3010 y
3011 (revappend (cdr x) (cons (car x) y))))
3012
3013 (defun nreconc (x y)
3014 "does (nconc (nreverse X) Y) would, only faster
3015 Destructive on X, be careful."
3016 (if (endp x)
3017 y
3018 ;; reuse the first cons of x, making it point to y
3019 (nreconc (cdr x) (prog1 x (rplacd x y)))))
3020
3021 (defun nbutlast (list &optional n)
3022 "Side-effected LIST truncated N+1 conses from the end.
3023 This is the destructive version of BUTLAST. Returns () and does not
3024 modify the LIST argument if the length of the list is not at least N."
3025 (when (null n) (setf n 1))
3026 (let ((length (list-length list)))
3027 (cond ((null length)
3028 list)
3029 ((< length n)
3030 '())
3031 (t
3032 (setnthcdr (- length n) list nil)
3033 list))))
3034 \f
3035 ;;; Substitutions
3036
3037 (defun subst (new old tree)
3038 "NEW replaces OLD in a copy of TREE
3039 Uses eql for the test."
3040 (subst-if new (function (lambda (x) (eql x old))) tree))
3041
3042 (defun subst-if-not (new test tree)
3043 "NEW replaces any subtree or leaf that fails TEST in a copy of TREE"
3044 ;; (subst-if new (function (lambda (x) (not (funcall test x)))) tree)
3045 (cond ((not (funcall test tree))
3046 new)
3047 ((atom tree)
3048 tree)
3049 (t ;no match so far
3050 (let ((head (subst-if-not new test (car tree)))
3051 (tail (subst-if-not new test (cdr tree))))
3052 ;; If nothing changed, return originals. Else use the new
3053 ;; components to assemble a new tree.
3054 (if (and (eql head (car tree))
3055 (eql tail (cdr tree)))
3056 tree
3057 (cons head tail))))))
3058
3059 (defun subst-if (new test tree)
3060 "NEW replaces any subtree or leaf that satisfies TEST in a copy of TREE"
3061 (cond ((funcall test tree)
3062 new)
3063 ((atom tree)
3064 tree)
3065 (t ;no match so far
3066 (let ((head (subst-if new test (car tree)))
3067 (tail (subst-if new test (cdr tree))))
3068 ;; If nothing changed, return originals. Else use the new
3069 ;; components to assemble a new tree.
3070 (if (and (eql head (car tree))
3071 (eql tail (cdr tree)))
3072 tree
3073 (cons head tail))))))
3074
3075 (defun sublis (alist tree)
3076 "Use association list ALIST to modify a copy of TREE
3077 If a subtree or leaf of TREE is a key in ALIST, it is replaced by the
3078 associated value. Not exactly Common Lisp, but close in spirit and
3079 compatible with the native Emacs Lisp ASSOC, which uses EQUAL."
3080 (let ((toplevel (assoc tree alist)))
3081 (cond (toplevel ;Bingo at top
3082 (cdr toplevel))
3083 ((atom tree) ;Give up on this
3084 tree)
3085 (t
3086 (let ((head (sublis alist (car tree)))
3087 (tail (sublis alist (cdr tree))))
3088 (if (and (eql head (car tree))
3089 (eql tail (cdr tree)))
3090 tree
3091 (cons head tail)))))))
3092
3093 (defun member-if (predicate list)
3094 "PREDICATE is applied to the members of LIST. As soon as one of them
3095 returns true, that tail of the list if returned. Else NIL."
3096 (catch 'found-member-if
3097 (while (not (endp list))
3098 (if (funcall predicate (car list))
3099 (throw 'found-member-if list)
3100 (setq list (cdr list))))
3101 nil))
3102
3103 (defun member-if-not (predicate list)
3104 "PREDICATE is applied to the members of LIST. As soon as one of them
3105 returns false, that tail of the list if returned. Else NIL."
3106 (catch 'found-member-if-not
3107 (while (not (endp list))
3108 (if (funcall predicate (car list))
3109 (setq list (cdr list))
3110 (throw 'found-member-if-not list)))
3111 nil))
3112
3113 (defun tailp (sublist list)
3114 "(tailp SUBLIST LIST) => True if SUBLIST is a sublist of LIST."
3115 (catch 'tailp-found
3116 (while (not (endp list))
3117 (if (eq sublist list)
3118 (throw 'tailp-found t)
3119 (setq list (cdr list))))
3120 nil))
3121 \f
3122 ;;; Suggestion of phr%widow.Berkeley.EDU@lilac.berkeley.edu
3123
3124 (defmacro declare (&rest decls)
3125 "Ignore a Common-Lisp declaration."
3126 "declarations are ignored in this implementation")
3127
3128 (defun proclaim (&rest decls)
3129 "Ignore a Common-Lisp proclamation."
3130 "declarations are ignored in this implementation")
3131
3132 (defmacro the (type form)
3133 "(the TYPE FORM) macroexpands to FORM
3134 No checking is even attempted. This is just for compatibility with
3135 Common-Lisp codes."
3136 form)
3137 \f
3138 ;;; Due to Aaron Larson (alarson@src.honeywell.com, 26 Jul 91)
3139 (put 'progv 'common-lisp-indent-hook '(4 4 &body))
3140 (defmacro progv (vars vals &rest body)
3141 "progv vars vals &body forms
3142 bind vars to vals then execute forms.
3143 If there are more vars than vals, the extra vars are unbound, if
3144 there are more vals than vars, the extra vals are just ignored."
3145 (` (progv$runtime (, vars) (, vals) (function (lambda () (,@ body))))))
3146
3147 ;;; To do this efficiently, it really needs to be a special form...
3148 (defun progv$runtime (vars vals body)
3149 (eval (let ((vars-n-vals nil)
3150 (unbind-forms nil))
3151 (do ((r vars (cdr r))
3152 (l vals (cdr l)))
3153 ((endp r))
3154 (push (list (car r) (list 'quote (car l))) vars-n-vals)
3155 (if (null l)
3156 (push (` (makunbound '(, (car r)))) unbind-forms)))
3157 (` (let (, vars-n-vals) (,@ unbind-forms) (funcall '(, body)))))))
3158
3159 (provide 'cl)
3160
3161 ;;;; end of cl.el