Loading [MathJax]/extensions/tex2jax.js

2010年7月15日木曜日

Modified run-length encoding

;; P11 (*) Modified run-length encoding.
;; Modify the result of problem P10 in such a way that if an element has no duplicates it is simply copied into the result list. Only elements with duplicates are transferred as (N E) lists.
;; Example:
;; * (encode-modified '(a a a a b c c a a d e e e e))
;; ((4 A) B (2 C) (2 A) D (4 E))
(require srfi/1)
(define (encode lst)
(let loop ((lst lst) (acc '()))
(if (null? lst)
(reverse acc)
(loop (strip lst)
(cons
(let ((head (car lst))
(len (length (picks lst))))
(if (= len 1)
head
`(,len ,head)))
acc)))))
(define-syntax define-encode-aux
(syntax-rules ()
((_ name proc)
(define (name lst)
(let ((head (car lst)))
(proc (lambda (x)
(eq? head x)) lst))))))
;; Using a procedure, take-while, defined in SRFI-1
(define-encode-aux picks take-while)
;; Using a procedure, drop-while, defined in SRFI-1
(define-encode-aux strip drop-while)
view raw p11.ss hosted with ❤ by GitHub

0 件のコメント:

コメントを投稿