aboutsummaryrefslogtreecommitdiff
path: root/p99/p09.neb
blob: 619c4a4387974f21693ca38fe811ee3ebcbbb0a8 (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
; P09 Pack consecutive duplicates of list elements into sublists.
; If a list contains repeated elements they should be placed in separate sublists.

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

; the list, the most recent value, the accumulator
(func pack-dup (lst)
    (pack-dup lst "" (list)))

(func pack-dup (lst prev acc)
    (branch
        ((empty? lst) acc) ; if we're done, return acc
        ((eq? (first lst) prev) ; the item is the same as the previous item
            (pack-dup 
                (rest lst) 
                prev 
                (append  ; add item to the last list in acc
                    (most acc) 
                    (append 
                        (last acc) 
                        prev))))
        (#true
            (pack-dup 
                (rest lst) 
                (first lst) 
                (append 
                    acc 
                    (list (first lst)))))))  ; add new list with this item

(print (->string a))
(print (->string (pack-dup a)))