aboutsummaryrefslogtreecommitdiff
path: root/p99/p12.neb
blob: 7d8ec4ef069ad5c989712c98b8f2168e96a53493 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
; P12 Decode a run-length encoded list.
; Given a run-length code list generated as specified in problem P11.
; Construct its uncompressed version.

(def a (list (list 4 "a") "b" (list 2 "c") (list 2 "a") "d" (list 4 "e")))

(func extend (lst1 lst2)
    (reduce append lst2 lst1))

(func flatten (lst)
    (reduce
        (lambda (x y) (extend x y))
        lst
        (list)))

(func decode (lst)
    (flatten
        (map
            (lambda (item)
                (if (eq? 1 (length item)) 
                    (list item) 
                    (rpt (first item) (last item)))) 
            lst)))
            
(func rpt (cnt let)
    (if (eq? cnt 1)
        (list let)
        (extend (list let) (rpt (- cnt 1) let))))

; iterative
(func rpt-iter (cnt let)
    (def out (list))
    (for-count cnt
        (redef out (append out let)))
    out)

(print (->string (decode a)))