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