• P08 (**) Eliminate consecutive duplicates of list elements.

    From B. Pym@21:1/5 to All on Mon Aug 19 08:14:08 2024
    If a list contains repeated elements they should be replaced
    with a single copy of the element. The order of the elements
    should not be changed.

    Example:
    * (compress '(a a a a b c c a a d e e e e))
    (A B C A D E)

    In newLisp, "apply" can be used for reduce or fold.

    (define (compress lst)
    (reverse
    (apply
    (fn (accum x)
    (cond ((empty? accum) (list x))
    ((= x (first accum)) accum)
    (true (cons x accum))))
    (cons '() lst)
    2) ;; How many things to process at a time.
    ))

    (compress '(a a a a b c c a a d e e e e))
    ===>
    (a b c a d e)

    --- SoupGate-Win32 v1.05
    * Origin: fsxNet Usenet Gateway (21:1/5)
  • From B. Pym@21:1/5 to B. Pym on Mon Aug 19 09:09:57 2024
    B. Pym wrote:

    If a list contains repeated elements they should be replaced
    with a single copy of the element. The order of the elements
    should not be changed.

    Example:
    * (compress '(a a a a b c c a a d e e e e))
    (A B C A D E)

    In newLisp, "apply" can be used for reduce or fold.

    (define (compress lst)
    (reverse
    (apply
    (fn (accum x)
    (cond ((empty? accum) (list x))
    ((= x (first accum)) accum)
    (true (cons x accum))))
    (cons '() lst)
    2) ;; How many things to process at a time.
    ))

    (compress '(a a a a b c c a a d e e e e))
    ===>
    (a b c a d e)

    The list could first be converted to monotonic sublists.

    (define (monotonic-slices lst key-func (cmp =))
    (let (result '() tmp '() old-key 0 new-key 0)
    (dolist (x lst)
    (set 'new-key (key-func x))
    (cond ((empty? tmp) (push x tmp))
    ((cmp new-key old-key) (push x tmp))
    (true (push (reverse tmp) result) (set 'tmp (list x))))
    (set 'old-key new-key))
    (unless (empty? tmp) (push (reverse tmp) result))
    (reverse result)))

    (monotonic-slices '(0 2 3 4 5 7) odd?)
    ===>
    ((0 2) (3) (4) (5 7))

    (monotonic-slices '(0 2 3 3 4 8 7 9) or >)
    ===>
    ((0 2 3) (3 4 8) (7 9))


    So the solution to this problem is:

    (map first (monotonic-slices '(a a a a b c c a a d e e e e) or))
    ===>
    (a b c a d e)

    --- SoupGate-Win32 v1.05
    * Origin: fsxNet Usenet Gateway (21:1/5)