问题描述
在P10的算法实现中,若一个元素不连续重复,我们最终也转化为(N E)
的形式,即N
为1的特殊形式。 该题的要求是特殊处理这一情况,直接将元素复制到结果列表中。如
sash> (encode-modified '(a a a a b c c a a d e e e e))
sash> ((4 a) b (2 c) (2 a) d (4 e))
解法
按照题目要求,我们只修改let
绑定的局部enc
,即可。这是封装抽象的好处,能让修改局部化,利于逻辑清晰和维护,对现实中的大项目尤甚。
递归实现
(define encode-modified (lambda (ls) (let ([p (pack ls)] [enc (lambda (sub) (if (null? (cdr sub)) (car sub) (list (length sub) (car sub))))]) (let f ([p p]) (cond [(null? p) '()] [else (cons (enc (car p)) (f (cdr p)))])))))
reduce实现
(define encode-modified (lambda (ls) (let ([p (pack ls)] [enc (lambda (sub) (if (null? (cdr sub)) (car sub) (list (length sub) (car sub))))]) (fold-right (lambda (e a) (cons (enc e) a)) '() p))))
map实现
(define encode-modified (lambda (ls) (let ([p (pack ls)] [enc (lambda (sub) (if (null? (cdr sub)) (car sub) (list (length sub) (car sub))))]) (map (lambda (e) (enc e)) p))))