Idiomatic way to group a sorted list of integers?

common-lisp, lisp

Solution

Not that bad. I would write it this way:

(defun group (list)
  (flet ((take-same (item)
           (loop while (and list (eql (first list) item))
                 collect (pop list))))
    (loop while list
          collect (take-same (first list)))))


CL-USER 1 > (group '(1 2 4 5 6 6 7 8 10 10 10))
((1) (2) (4) (5) (6 6) (7) (8) (10 10 10))

Problem

I have a sorted list of integers, `(1 2 4 5 6 6 7 8 10 10 10)`. I want to group them all, so that I get `((1) (2) (4) (5) (6 6) (7) (8) (10 10 10))`. So far I have this, which works: ``` (let ((current-group (list)) (groups (list))) (dolist (n *sorted*) (when (and (not (null current-group)) (not (eql (first current-group) n))) (push current-group groups) (setf current-group (list))) (push n current-group)) (push current-group groups) (nreverse groups)) ``` But I'm sure there must be a much more LISPy way to do this. Any ideas?

Original source

Related problems