Path: news.eternal-september.org!eternal-september.org!.POSTED!not-for-mail From: "B. Pym" Newsgroups: comp.lang.lisp Subject: Re: Exercises please Date: Sat, 21 Jun 2025 20:26:29 -0000 (UTC) Organization: A noiseless patient Spider Lines: 64 Message-ID: <10374hj$191qo$1@dont-email.me> MIME-Version: 1.0 Content-Type: text/plain; charset=iso-8859-1 Injection-Date: Sat, 21 Jun 2025 22:26:29 +0200 (CEST) Injection-Info: dont-email.me; posting-host="b22693aa257d9a554fc4138883cff5f9"; logging-data="1345368"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX1/F0OCHvAAjvW86Gs7bQ4mL" User-Agent: XanaNews/1.18.1.6 Cancel-Lock: sha1:D+dTBcmqmuFc0b6SiKwFxVpgfS8= Pascal J. Bourguignon wrote: > and my solutions (still incomplete): > http://www.informatimago.com/develop/lisp/l99/index.html Where we find: (--------------------------------------------------------------- P13 (**) Run-length encoding of a list (direct solution). Example: * (encode-direct '(a a a a b c c a a d e e e e)) ((4 A) B (2 C) (2 A) D (4 E)) " ;; Iterative solution, uses only O(r) space: (defun encode-modified (list) (let ((result '()) (count 0) (last-item nil)) (labels ((collect-result () (push (if (= 1 count) last-item (list count last-item)) result)) (new-item (item) (setf count 1 last-item item)) (same-item () (incf count)) (return-result () (when (plusp count) (collect-result)) (nreverse result))) (dolist (item list (return-result)) (cond ((zerop count) (new-item item)) ((eql item last-item) (same-item)) (t (collect-result) (new-item item))))))) ---------------------------------------------------------------) Gauche Scheme (define (encode List) (if (null? List) () (let ((tmp (fold (lambda(x accum) (if (equal? x (caar accum)) (cons (cons x (car accum)) (cdr accum)) (cons (list x) accum))) `((,(car List))) (cdr List)))) (reverse (map (lambda(xs) (let1 len (length xs) (if (= 1 len) (car xs) (list len (car xs))))) tmp))))) gosh> (encode '(a a a a b c c a a d e e e e)) ((4 a) b (2 c) (2 a) d (4 e))