aboutsummaryrefslogtreecommitdiff
path: root/p99/p13.neb
blob: e32d8cb6b6795149e01b92187807a1f7795c75f0 (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
; P13 Run-length encoding of a list (direct solution).
; Implement the so-called run-length encoding data compression method directly. 
; I.e. don't explicitly create the sublists containing the duplicates, as in problem P09, 
; but only count them. As in problem P11, simplify the result list by replacing the 
; singleton lists (1 X) by X.

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

(func encode-direct (lst)
    (encode-direct lst "" (list)))

(func encode-direct (lst :nil prev acc)
    acc)

(func encode-direct (lst :{:any} prev acc)
    (if (eq? (first lst) prev)
        (encode-direct
            (rest lst)
            prev
            (append (most acc)
                (if (list? (last acc))
                    (list (+ 1 (first (last acc))) prev)
                    (list 2 prev))))
        (encode-direct
            (rest lst)
            (first lst)
            (append acc (first lst)))))

(print (->string a))
(print (->string (encode-direct a)))