chiark / gitweb /
collect: Provide functional interface for collectors.
authorMark Wooding <mdw@distorted.org.uk>
Sun, 24 Dec 2006 18:27:05 +0000 (18:27 +0000)
committerMark Wooding <mdw@distorted.org.uk>
Sun, 24 Dec 2006 18:27:05 +0000 (18:27 +0000)
collect.lisp

index 359780c5363fbb831fac52115a44256f180c0d36..cab2808d4e074b15d5c1dfdf4481df24359109aa 100644 (file)
 
 (defpackage #:collect
   (:use #:common-lisp #:mdw.base)
-  (:export #:collecting #:with-collection #:collect #:collect-tail))
+  (:export #:make-collector #:collected
+          #:collecting #:with-collection
+          #:collect #:collect-tail
+          #:collect-append #:collect-nconc))
 (in-package collect)
 
 (eval-when (:compile-toplevel :load-toplevel)
   (defvar *collecting-anon-list-name* (gensym)
-    "The default name for anonymous `collecting' lists.")
-  (defun make-collector ()
-    (let ((head (cons nil nil)))
-      (setf (car head) head))))
+    "The default name for anonymous `collecting' lists."))
+
+(defun make-collector (&optional list)
+  "Return a new collector object whose initial contents is LIST.  Note that
+   LIST will be destroyed if anything else is collected."
+  (let ((head (cons nil list)))
+    (setf (car head) (if list (last list) head))))
+
+(defmacro collected (&optional (name *collecting-anon-list-name*))
+  "Return the current list collected into the collector NAME (or
+   *collecting-anon-list-name* by default)."
+  `(the list (cdr ,name)))
 
 (defmacro collecting (vars &body body)
   "Collect items into lists.  The VARS are a list of collection variables --
@@ -45,7 +56,7 @@ (defmacro collecting (vars &body body)
        ((atom vars) (setf vars (list vars))))
   `(let ,(mapcar (lambda (v) `(,v (make-collector))) vars)
      ,@body
-     (values ,@(mapcar (lambda (v) `(the list (cdr ,v))) vars))))
+     (values ,@(mapcar (lambda (v) `(collected ,v)) vars))))
 
 (defmacro with-collection (vars collection &body body)
   "Collect items into lists VARS according to the form COLLECTION; then