除去相邻-重复

时间:2018-04-17 12:04:35

标签: scheme racket

我想实现一个函数,它以列表作为输入并返回值作为值,同一列表中任何重复元素序列都缩减为单个元素:

示例:

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

我已设法使用以下代码执行此操作:

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

但是代码并不漂亮且包含循环我希望使用诸如'car''cdr'和'cons'之类的实用程序的递归代码。

1 个答案:

答案 0 :(得分:1)

loop是内部过程的名称,递归调用;查找named lets。你可以把它命名为你想要的;在我的例子中,我称它为iter以避免这种混淆。

您还可以简化一下:

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