blog/content/post/2010/11/24/2010-11-24-00001430.md

5.5 KiB
Raw Blame History

title author date wordtwit_post_info categories
Ninety-nine Lisp Problems P10の解答 kazu634 2010-11-24
O:8:"stdClass":13:{s:6:"manual";b:0;s:11:"tweet_times";i:1;s:5:"delay";i:0;s:7:"enabled";i:1;s:10:"separation";s:2:"60";s:7:"version";s:3:"3.7";s:14:"tweet_template";b:0;s:6:"status";i:2;s:6:"result";a:0:{}s:13:"tweet_counter";i:2;s:13:"tweet_log_ids";a:1:{i:0;i:5389;}s:9:"hash_tags";a:0:{}s:8:"accounts";a:1:{i:0;s:7:"kazu634";}}
gauche
Lisp

P9の解答で作成した関数を元にして、リスト空リストへの変換を行う形で解答を作成してみました。つまり

  1. packでリストを作成する
  2. packで作られたリストの中のリストを変換する手続きencode-listを作成する
  3. packに対してencode-listをmapする

感じでやってみました。

ソース

;; 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))
(define (pack-seed front sublist result l)
(cond
[(null? l) (append result (list sublist))]
[(eq? front (car l)) (pack-seed front
(append sublist
(list front))
result
(cdr l))]
[else (pack-seed (car l)
(list (car l))
(if (null? result)
(if (null? sublist)
'()
(append result (list sublist)))
(append result (list sublist)))
(cdr l))]))
(define (pack l)
(pack-seed #f '() '() l))
(define (encode-list l)
(let ((num (length l)))
(append (list num)
(list (car l)))))
(encode-list '(a a a a a))
(define (encode l)
(map (lambda (l)
(encode-list l))
(pack l)))
(encode '(a a a a b c c a a d e e e e))