(defun compress (x) ;; compress takes a list of atoms and returns a compressed representation for it ;; whenever the same element occurs several times in a row, ;; the sequence is replaced by a list indicating the element and ;; the number of occurrences ;; First, compress checks that it's argument is a list (if (consp x) (compr (car x) 1 (cdr x)) x)) (defun compr (elt n lst) ;; compr traverses the list recursively. ;; If the current element is equal to the next, increments the counter "n" ;; If not, it builds a portion of the result, and continues the recursion on ;; the rest of the list, but resets the counter to 1 (if (null lst) (list (n-elts elt n)) (let ((next (car lst))) (if (eql next elt) (compr elt (+ n 1) (cdr lst)) (cons (n-elts elt n) (compr next 1 (cdr lst))) ) ) ) ) (defun n-elts (elt n) ; builds an element of the result for compr (if (> n 1) (list n elt) elt))