lists.lisp 13.7 KB
Newer Older
Nikodemus Siivola's avatar
Nikodemus Siivola committed
1 2
(in-package :alexandria)

3 4 5 6 7
(declaim (inline safe-endp))
(defun safe-endp (x)
  (declare (optimize safety))
  (endp x))

8 9 10 11 12 13 14 15 16 17 18 19 20 21
(defun alist-plist (alist)
  "Returns a property list containing the same keys and values as the
association list ALIST in the same order."
  (let (plist)
    (dolist (pair alist)
      (push (car pair) plist)
      (push (cdr pair) plist))
    (nreverse plist)))

(defun plist-alist (plist)
  "Returns an association list containing the same keys and values as the
property list PLIST in the same order."
  (let (alist)
    (do ((tail plist (cddr tail)))
22
        ((safe-endp tail) (nreverse alist))
23 24
      (push (cons (car tail) (cadr tail)) alist))))

25 26 27 28
(declaim (inline racons))
(defun racons (key value ralist)
  (acons value key ralist))

29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
(macrolet
    ((define-alist-get (name get-entry get-value-from-entry add doc)
       `(progn
          (declaim (inline ,name))
          (defun ,name (alist key &key (test 'eql))
            ,doc
            (let ((entry (,get-entry key alist :test test)))
              (values (,get-value-from-entry entry) entry)))
          (define-setf-expander ,name (place key &key (test ''eql)
                                       &environment env)
            (multiple-value-bind
                  (temporary-variables initforms newvals setter getter)
                (get-setf-expansion place env)
              (when (cdr newvals)
                (error "~A cannot store multiple values in one place" ',name))
44
              (with-unique-names (new-value key-val test-val alist entry)
45 46 47 48 49 50 51 52 53 54 55
                (values
                 (append temporary-variables
                         (list alist
                               key-val
                               test-val
                               entry))
                 (append initforms
                         (list getter
                               key
                               test
                               `(,',get-entry ,key-val ,alist :test ,test-val)))
56
                 `(,new-value)
57 58
                 `(cond
                    (,entry
59
                     (setf (,',get-value-from-entry ,entry) ,new-value))
60 61
                    (t
                     (let ,newvals
62 63 64
                       (setf ,(first newvals) (,',add ,key ,new-value ,alist))
                       ,setter
                       ,new-value)))
65
                 `(,',get-value-from-entry ,entry))))))))
66 67 68 69 70 71 72
 (define-alist-get assoc-value assoc cdr acons
"ASSOC-VALUE is an alist accessor very much like ASSOC, but it can
be used with SETF.")
 (define-alist-get rassoc-value rassoc car racons
"RASSOC-VALUE is an alist accessor very much like RASSOC, but it can
be used with SETF."))

Nikodemus Siivola's avatar
Nikodemus Siivola committed
73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
(defun malformed-plist (plist)
  (error "Malformed plist: ~S" plist))

(defmacro doplist ((key val plist &optional values) &body body)
  "Iterates over elements of PLIST. BODY can be preceded by
declarations, and is like a TAGBODY. RETURN may be used to terminate
the iteration early. If RETURN is not used, returns VALUES."
  (multiple-value-bind (forms declarations) (parse-body body)
    (with-gensyms (tail loop results)
      `(block nil
         (flet ((,results ()
                  (let (,key ,val)
                    (declare (ignorable ,key ,val))
                    (return ,values))))
           (let* ((,tail ,plist)
                  (,key (if ,tail
                            (pop ,tail)
                            (,results)))
                 (,val (if ,tail
                           (pop ,tail)
                           (malformed-plist ',plist))))
            (declare (ignorable ,key ,val))
            ,@declarations
            (tagbody
               ,loop
               ,@forms
               (setf ,key (if ,tail
                              (pop ,tail)
                              (,results))
                     ,val (if ,tail
                              (pop ,tail)
                              (malformed-plist ',plist)))
               (go ,loop))))))))

Nikodemus Siivola's avatar
Nikodemus Siivola committed
107 108 109 110
(define-modify-macro appendf (&rest lists) append
  "Modify-macro for APPEND. Appends LISTS to the place designated by the first
argument.")

Luis Oliveira's avatar
Luis Oliveira committed
111 112 113 114
(define-modify-macro nconcf (&rest lists) nconc
  "Modify-macro for NCONC. Concatenates LISTS to place designated by the first
argument.")

115
(define-modify-macro unionf (list &rest args) union
116 117 118
  "Modify-macro for UNION. Saves the union of LIST and the contents of the
place designated by the first argument to the designated place.")

119
(define-modify-macro nunionf (list &rest args) nunion
120 121 122 123
  "Modify-macro for NUNION. Saves the union of LIST and the contents of the
place designated by the first argument to the designated place. May modify
either argument.")

124 125 126 127 128 129 130 131
(define-modify-macro reversef () reverse
  "Modify-macro for REVERSE. Copies and reverses the list stored in the given
place and saves back the result into the place.")

(define-modify-macro nreversef () nreverse
  "Modify-macro for NREVERSE. Reverses the list stored in the given place by
destructively modifying it and saves back the result into the place.")

Nikodemus Siivola's avatar
Nikodemus Siivola committed
132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153
(defun circular-list (&rest elements)
  "Creates a circular list of ELEMENTS."
  (let ((cycle (copy-list elements)))
    (nconc cycle cycle)))

(defun circular-list-p (object)
  "Returns true if OBJECT is a circular list, NIL otherwise."
  (and (listp object)
       (do ((fast object (cddr fast))
            (slow (cons (car object) (cdr object)) (cdr slow)))
           (nil)
         (unless (and (consp fast) (listp (cdr fast)))
           (return nil))
         (when (eq fast slow)
           (return t)))))

(defun circular-tree-p (object)
  "Returns true if OBJECT is a circular tree, NIL otherwise."
  (labels ((circularp (object seen)
             (and (consp object)
                  (do ((fast (cons (car object) (cdr object)) (cddr fast))
                       (slow object (cdr slow)))
154
                      (nil)
Nikodemus Siivola's avatar
Nikodemus Siivola committed
155
                    (when (or (eq fast slow) (member slow seen))
156 157 158 159 160 161 162 163
                      (return-from circular-tree-p t))
                    (when (or (not (consp fast)) (not (consp (cdr slow))))
                      (return
                        (do ((tail object (cdr tail)))
                            ((not (consp tail))
                             nil)
                          (let ((elt (car tail)))
                            (circularp elt (cons object seen))))))))))
Nikodemus Siivola's avatar
Nikodemus Siivola committed
164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181
    (circularp object nil)))

(defun proper-list-p (object)
  "Returns true if OBJECT is a proper list."
  (cond ((not object)
         t)
        ((consp object)
         (do ((fast object (cddr fast))
              (slow (cons (car object) (cdr object)) (cdr slow)))
             (nil)
           (unless (and (listp fast) (consp (cdr fast)))
             (return (and (listp fast) (not (cdr fast)))))
           (when (eq fast slow)
             (return nil))))
        (t
         nil)))

(deftype proper-list ()
Nikodemus Siivola's avatar
Nikodemus Siivola committed
182 183
  "Type designator for proper lists. Implemented as a SATISFIES type, hence
not recommended for performance intensive use. Main usefullness as a type
Attila Lendvai's avatar
Attila Lendvai committed
184
designator of the expected type in a TYPE-ERROR."
185
  `(and list (satisfies proper-list-p)))
Nikodemus Siivola's avatar
Nikodemus Siivola committed
186

187 188 189 190 191 192 193 194 195 196 197 198 199 200
(defun circular-list-error (list)
  (error 'type-error
         :datum list
         :expected-type '(and list (not circular-list))))

(macrolet ((def (name lambda-list doc step declare ret1 ret2)
             (assert (member 'list lambda-list))
             `(defun ,name ,lambda-list
                ,doc
                (do ((last list fast)
                     (fast list (cddr fast))
                     (slow (cons (car list) (cdr list)) (cdr slow))
                     ,@(when step (list step)))
                    (nil)
201 202
                  (declare (dynamic-extent slow) ,@(when declare (list declare))
                           (ignorable last))
203 204 205 206 207 208 209 210 211 212 213 214
                  (when (safe-endp fast)
                    (return ,ret1))
                  (when (safe-endp (cdr fast))
                    (return ,ret2))
                  (when (eq fast slow)
                    (circular-list-error list))))))
  (def proper-list-length (list)
    "Returns length of LIST, signalling an error if it is not a proper list."
    (n 1 (+ n 2))
    ;; KLUDGE: Most implementations don't actually support lists with bignum
    ;; elements -- and this is WAY faster on most implementations then declaring
    ;; N to be an UNSIGNED-BYTE.
215
    (fixnum n)
216 217
    (1- n)
    n)
218

219 220
  (def lastcar (list)
      "Returns the last element of LIST. Signals a type-error if LIST is not a
Nikodemus Siivola's avatar
Nikodemus Siivola committed
221
proper list."
222 223 224 225
    nil
    nil
    (cadr last)
    (car fast))
226

227 228
  (def (setf lastcar) (object list)
      "Sets the last element of LIST. Signals a type-error if LIST is not a proper
229
list."
230 231 232 233
    nil
    nil
    (setf (cadr last) object)
    (setf (car fast) object)))
234

Nikodemus Siivola's avatar
Nikodemus Siivola committed
235 236 237 238 239 240
(defun make-circular-list (length &key initial-element)
  "Creates a circular list of LENGTH with the given INITIAL-ELEMENT."
  (let ((cycle (make-list length :initial-element initial-element)))
    (nconc cycle cycle)))

(deftype circular-list ()
Nikodemus Siivola's avatar
Nikodemus Siivola committed
241 242 243
  "Type designator for circular lists. Implemented as a SATISFIES type, so not
recommended for performance intensive use. Main usefullness as the
expected-type designator of a TYPE-ERROR."
Nikodemus Siivola's avatar
Nikodemus Siivola committed
244 245
  `(satisfies circular-list-p))

Nikodemus Siivola's avatar
Nikodemus Siivola committed
246 247 248 249 250 251
(defun ensure-car (thing)
  "If THING is a CONS, its CAR is returned. Otherwise THING is returned."
  (if (consp thing)
      (car thing)
      thing))

252 253 254 255 256 257 258
(defun ensure-cons (cons)
  "If CONS is a cons, it is returned. Otherwise returns a fresh cons with CONS
  in the car, and NIL in the cdr."
  (if (consp cons)
      cons
      (cons cons nil)))

Nikodemus Siivola's avatar
Nikodemus Siivola committed
259 260 261 262 263 264
(defun ensure-list (list)
  "If LIST is a list, it is returned. Otherwise returns the list designated by LIST."
  (if (listp list)
      list
      (list list)))

265
(defun remove-from-plist (plist &rest keys)
266 267 268
  "Returns a propery-list with same keys and values as PLIST, except that keys
in the list designated by KEYS and values corresponding to them are removed.
The returned property-list may share structure with the PLIST, but PLIST is
269
not destructively modified. Keys are compared using EQ."
270
  (declare (optimize (speed 3)))
271 272 273 274
  ;; FIXME: possible optimization: (remove-from-plist '(:x 0 :a 1 :b 2) :a)
  ;; could return the tail without consing up a new list.
  (loop for (key . rest) on plist by #'cddr
        do (assert rest () "Expected a proper plist, got ~S" plist)
275
        unless (member key keys :test #'eq)
276
        collect key and collect (first rest)))
Nikodemus Siivola's avatar
Nikodemus Siivola committed
277

278 279
(defun delete-from-plist (plist &rest keys)
  "Just like REMOVE-FROM-PLIST, but this version may destructively modify the
280
provided PLIST."
281
  (declare (optimize speed))
282 283 284 285 286 287 288 289 290 291 292 293 294
  (loop with head = plist
        with tail = nil   ; a nil tail means an empty result so far
        for (key . rest) on plist by #'cddr
        do (assert rest () "Expected a proper plist, got ~S" plist)
           (if (member key keys :test #'eq)
               ;; skip over this pair
               (let ((next (cdr rest)))
                 (if tail
                     (setf (cdr tail) next)
                     (setf head next)))
               ;; keep this pair
               (setf tail rest))
        finally (return head)))
295

Nikodemus Siivola's avatar
Nikodemus Siivola committed
296 297 298 299
(define-modify-macro remove-from-plistf (&rest keys) remove-from-plist
                     "Modify macro for REMOVE-FROM-PLIST.")
(define-modify-macro delete-from-plistf (&rest keys) delete-from-plist
                     "Modify macro for DELETE-FROM-PLIST.")
300

301 302 303 304 305
(declaim (inline sans))
(defun sans (plist &rest keys)
  "Alias of REMOVE-FROM-PLIST for backward compatibility."
  (apply #'remove-from-plist plist keys))

Nikodemus Siivola's avatar
Nikodemus Siivola committed
306 307 308 309 310 311
(defun mappend (function &rest lists)
  "Applies FUNCTION to respective element(s) of each LIST, appending all the
all the result list to a single list. FUNCTION must return a list."
  (loop for results in (apply #'mapcar function lists)
        append results))

312 313 314 315 316 317 318
(defun setp (object &key (test #'eql) (key #'identity))
  "Returns true if OBJECT is a list that denotes a set, NIL otherwise. A list
denotes a set if each element of the list is unique under KEY and TEST."
  (and (listp object)
       (let (seen)
         (dolist (elt object t)
           (let ((key (funcall key elt)))
319
             (if (member key seen :test test)
320 321 322 323
                 (return nil)
                 (push key seen)))))))

(defun set-equal (list1 list2 &key (test #'eql) (key nil keyp))
Nikodemus Siivola's avatar
Nikodemus Siivola committed
324 325
  "Returns true if every element of LIST1 matches some element of LIST2 and
every element of LIST2 matches some element of LIST1. Otherwise returns false."
326 327 328 329 330 331 332 333 334 335 336 337 338 339 340
  (let ((keylist1 (if keyp (mapcar key list1) list1))
        (keylist2 (if keyp (mapcar key list2) list2)))
    (and (dolist (elt keylist1 t)
           (or (member elt keylist2 :test test)
               (return nil)))
         (dolist (elt keylist2 t)
           (or (member elt keylist1 :test test)
               (return nil))))))

(defun map-product (function list &rest more-lists)
  "Returns a list containing the results of calling FUNCTION with one argument
from LIST, and one from each of MORE-LISTS for each combination of arguments.
In other words, returns the product of LIST and MORE-LISTS using FUNCTION.

Example:
341

Nikodemus Siivola's avatar
Nikodemus Siivola committed
342 343 344
 (map-product 'list '(1 2) '(3 4) '(5 6))
  => ((1 3 5) (1 3 6) (1 4 5) (1 4 6)
      (2 3 5) (2 3 6) (2 4 5) (2 4 6))
345 346 347 348 349 350 351 352 353
"
  (labels ((%map-product (f lists)
             (let ((more (cdr lists))
                   (one (car lists)))
               (if (not more)
                   (mapcar f one)
                   (mappend (lambda (x)
                              (%map-product (curry f x) more))
                            one)))))
354
    (%map-product (ensure-function function) (cons list more-lists))))
Nikodemus Siivola's avatar
Nikodemus Siivola committed
355

356 357 358 359 360 361
(defun flatten (tree)
  "Traverses the tree in order, collecting non-null leaves into a list."
  (let (list)
    (labels ((traverse (subtree)
               (when subtree
                 (if (consp subtree)
362
                     (progn
363 364 365 366 367
                       (traverse (car subtree))
                       (traverse (cdr subtree)))
                     (push subtree list)))))
      (traverse tree))
    (nreverse list)))