Adam Morad
Adam Morad

Reputation: 167

Scheme remove adjacent duplicates

Trying to implement a procedure that removes adjacent duplicates. It 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))
'(y a b a d a b a d o)

(remove-adjacent-duplicates ’(yeah yeah yeah))
'(yeah)

How can this be done?

Upvotes: 0

Views: 477

Answers (2)

Adam Morad
Adam Morad

Reputation: 167

Here's a solution - first we check if the list is empty, if not - check for duplicates by chunks.

(define (strip-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)))))))))

Upvotes: 2

Sylwester
Sylwester

Reputation: 48745

Here is how to do it:

If the argument is the empty list or the cdr is the empty list then the result is the argument.

Else if the first and the second element is the same, then skip the first element.

Else cons the first element with the recursion with the cdr or the argument.. eg.

(remove-adjacent-duplicates '(a b)) ; ==
(cons (car '(a b)) (remove-adjacent-duplicates (cdr '(a b))))

Upvotes: 1

Related Questions