Loading [MathJax]/extensions/tex2jax.js

2010年7月15日木曜日

Run-length encoding of a list

;; P10 (*) Run-length encoding of a list.
;; Use the result of problem P09 to implement the so-called run-length encoding data compression method. Consecutive duplicates of elements are encoded as lists (N E) where N is the number of duplicates of the element E.
;; Example:
;; * (encode '(a a a a b c c a a d e e e e))
;; ((4 A) (1 B) (2 C) (2 A) (1 D)(4 E))
#lang racket
(provide encode)
(require srfi/1)
(define (encode lst)
(let loop ((lst lst) (acc '()))
(if (null? lst)
(reverse acc)
(loop (strip lst)
(cons
`(,(length (picks lst)) ,(car lst))
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 p10.ss hosted with ❤ by GitHub

0 件のコメント:

コメントを投稿