Loading [MathJax]/extensions/tex2jax.js

2010年7月15日木曜日

Run-length encoding of a list (direct solution)

;; P13 (**) Run-length encoding of a list (direct solution).
;; Implement the so-called run-length encoding data compression method directly. I.e. don't explicitly create the sublists containing the duplicates, as in problem P09, but only count them. As in problem P11, simplify the result list by replacing the singleton lists (1 X) by X.
;; 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))
;; Basd on the implementation of Paul Graham's ANSI Common Lisp
(define (encode-direct x)
(if (pair? x)
(compress (car x) 1 (cdr x))
x))
(define (compress elt n lst)
(let loop ((elt elt) (n n) (lst lst) (acc '()))
(let ((cna (cons (n-elts elt n) acc)))
(if (null? lst)
(reverse cna)
(let ((next (car lst))
(tail (cdr lst)))
(if (eq? next elt)
(loop elt (+ n 1) tail acc)
(loop next 1 tail cna)))))))
(define (n-elts elt n)
(if (> n 1)
`(,n ,elt)
elt))
view raw p13.ss hosted with ❤ by GitHub

0 件のコメント:

コメントを投稿