Reputation: 11
I start studying Lisp and I find a code on the book as example but I do not understand what is it for. Are you able to help me understanding that? I don't know if it is the right place to do it. Thanks everyone
(defun compress (l1)
(cond ((null (cdr l1)) '())
(t (accumula (car l1) 1 (cdr l1)))))
(defun accumula (val acc lst)
(cond ((null lst) (cons (comp-list val acc) nil))
((eq val (car lst)) (accumula val (1+ acc) (cdr lst)))
(t (cons (comp-list val acc) (accumula (car lst) 1 (cdr lst))))))
(defun comp-list (val acc)
(if (> acc 1) (list acc val) val))
Upvotes: 0
Views: 538
Reputation: 48745
This is an answer to problem 13 in The 99 Lisp problems (L99). It has a bug:
(compress '(a))
; ==> nil
The correct result would have been (a)
.
Upvotes: 1
Reputation: 180788
It's a compression function, of the Run Length Encoding variety.
(compress '(3 3 4 3 3 2 1 1 1 1 0))
will yield
((2 3) 4 (2 3) 2 (4 1) 0)
where the first number in each sublist is the number of times the second number repeats in the original sequence.
It doesn't look like much from the example, but for long sequences where numbers repeat a lot, you can get significant savings in storage costs.
Upvotes: 1