1. There's a sample program called run-length encoding: compression from
Ansi Common Lisp (Graham) pp. 37
(defun compress (x)
(if (consp x)
(compr (car x) 1 (cdr x))
x))
(defun compr (elt n lst)
(if (null lst)
(list (n-elts elt n))
(let ((next (car lst)))
(if (eql next elt)
(compr elt (+ 1 1) (cdr lst))
(cons (n-elts elt n)
(compr next 1 (cdr lst)))))))
(defun n-elts (elt n)
(if (> n 1)
(list n elt)
elt))
> (compress '(1 1 1 0 1 0 0 0 0 1))
((3 1) 0 1 (4 0) 1)
In compr, what is the reason for (list.... ? Why can't the third line of
compr just read (n-elts elt n)? - I think that for all cases the output is
equivalent.
2. I use ilisp-5.9.4. Is there anyway to correct the indentation of the
first two lines (under CMUCL-18b).
Instead of :
* (defun example .....
(second line, the leading parenthesis is lined up with the parenthesis
of the first line.
I can get:
* (defun example.....
(the second (and subsequent lines) are indented properly.
Ok, thanks for your help. These sort of (admittedly) minor points always
seem to drive me crazy.
-Half Kettle.
In article <············@news4.jaring.my>,
Half Kettle <·······@pd.jaring.my> wrote:
>1. There's a sample program called run-length encoding: compression from
>Ansi Common Lisp (Graham) pp. 37
>
>(defun compress (x)
> (if (consp x)
> (compr (car x) 1 (cdr x))
> x))
>
>(defun compr (elt n lst)
> (if (null lst)
> (list (n-elts elt n))
> (let ((next (car lst)))
> (if (eql next elt)
> (compr elt (+ 1 1) (cdr lst))
> (cons (n-elts elt n)
> (compr next 1 (cdr lst)))))))
>
>(defun n-elts (elt n)
> (if (> n 1)
> (list n elt)
> elt))
>
>> (compress '(1 1 1 0 1 0 0 0 0 1))
>((3 1) 0 1 (4 0) 1)
>
>In compr, what is the reason for (list.... ? Why can't the third line of
>compr just read (n-elts elt n)? - I think that for all cases the output is
>equivalent.
compr is supposed to return a list, where each element of the result is
either an element of the original list or a list (<count> <original>). The
line you refer to is the bottoming-out case for the recursion, but it still
has to follow that requirement: it has to return a list of new elements, so
it calls list to make a one-element list.
Compare:
Expression Book's result Your result
---------- ------------- -----------
(compress '(1)) (1) 1
(compress '(1 2) (1 2) (1 . 2)
(compress '(1 2 2 2) (1 (3 2)) (1 3 2)
Basically, you're removing a level of nesting from the last element.
--
Barry Margolin, ······@bbnplanet.com
GTE Internetworking, Powered by BBN, Burlington, MA
*** DON'T SEND TECHNICAL QUESTIONS DIRECTLY TO ME, post them to newsgroups.
Please DON'T copy followups to me -- I'll assume it wasn't posted to the group.