0

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))
7
  • 1
    This page provides some sample input and output to demonstrate the function. (compress '(3 3 4 3 3 2 1 1 1 1 0)) yields ((2 3) 4 (2 3) 2 (4 1) 0) Commented Jan 4, 2017 at 15:55
  • Is there a defined function called "compress" in lisp? Commented Jan 4, 2017 at 16:01
  • I don't know. I doubt it. Maybe in Common Lisp. Commented Jan 4, 2017 at 16:02
  • Is there a way to "sum" the common results? For example (2 3) 4 (2 3) will be (4 3) 4 2 (4 1) 0 Commented Jan 4, 2017 at 16:03
  • You could, but you would lose the compression information; i.e. you would no longer be able to reconstruct the original list. Compression is supposed to be reversible. Commented Jan 4, 2017 at 16:04

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks @Robert for making it. I will try to compress again trying to do (4 3) 4 2... Which is basically what I need. I find it quite difficult
Just understand that you won't be able to reconstruct the original sequence if you do that, because you will lose the positioning information (where the 3's were located in the original sequence).
Yes I perfectly understand that I will lose the sort property. It is just a way to do a difficult exercise
1

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).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.