S-99-11


S-99-11 Modified run-length encoding.

Modify the result of problem S-99-10 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)) 

Solution:

We'll reuse the helper function encode-f we defined for problem S-99-10 and simply pass it a modified encoder function:

 (define encode-modified 
   (lambda (xs) 
     (let ((encoder (lambda (pkg) 
                      (let ((N (length pkg)) 
                            (E (car pkg))) 
                        (if (= N 1) E (list N E)))))) 
       (encode-f xs encoder))))