0
votes

I want to implement a function which takes a list as input and returns as value the same list with any sequence of repeated elements reduced to a single element:

Example:

(remove-adjacent-duplicates ’(y a b b a d a b b a d o o)) ; the return'(y a b a d a b a d o)

(remove-adjacent-duplicates ’(yeah yeah yeah)) ;the return '(yeah)

I have managed to do this with the following code:

(define (remove-adjacent-duplicates ls)
  (if (null? ls)
      '()
      (let ((first (car ls)))
        (let loop ((known first)
                   (rest (cdr ls))
                   (so-far (list first)))
          (if (null? rest)
              (reverse so-far)
              (let ((first-remaining (car rest)))
                (loop first-remaining
                      (cdr rest)
                      (if (equal? known first-remaining)
                          so-far
                          (cons first-remaining so-far))))))))) 

But the code is not pretty and contains loop I want a recursion code using utilities such as 'car' 'cdr' and 'cons'.

1

1 Answers

1
votes

loop is the name of an inner procedure and is called recursively; look up named lets. You can name it what you want; in my example I have called it iter to avoid this confusion.

You can also simplify a little:

(define (remove-adjacent-duplicates lst)
  (let iter ((lst lst) (res '()))
    (if (null? lst)
        (reverse res)
        (let ((next (car lst)))
          (iter (cdr lst)
                (if (or (null? res) (not (equal? next (car res))))
                    (cons next res)
                    res))))))