打印列表的相邻重复项(方案) [英] Print adjacent duplicates of a list (scheme)

查看:114
本文介绍了打印列表的相邻重复项(方案)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个返回列表的相邻重复项的函数,例如(dups'(1 2 1 1 1 4 4)应该返回列表(1 4).

I'm trying to create a function that returns the adjacent duplicates of a list, for example (dups '(1 2 1 1 1 4 4) should return the list (1 4).

这是我到目前为止想出的代码:

This is the code I came up with so far:

(define (dups lst)
    (if (equal? (car lst)(car(cdr lst)))
        (cons(cdr lst) '())
        (dups(cdr lst))))

此函数不会返回所有相邻的重复项,而只会返回第一个相邻的重复项! 如何修复它,使其返回列表的所有相邻重复项?

This function doesn't return all the adjacent duplicates, it only returns the first adjacent duplicates! How can I fix it so that it returns all the adjacent duplicates of a list?

谢谢.

推荐答案

一旦您的代码发现重复项,它将停止处理列表的其余部分:当if测试为true时,将产生(cons (cdr lst) '()).无论是否找到重复项,它都应该仍在调用dups来处理列表的其余部分.

Once your code finds a duplicate, it stops processing the rest of the list: when the if test is true, it yields (cons (cdr lst) '()). Whether or not it finds a duplicate, it should still be calling dups to process the rest of the list.

此外:如果您的列表没有重复项,则会遇到麻烦.

Also: if your list has no duplicates, it it going to run into trouble.

这是比发布的其他解决方案更简单的解决方案:

Here's a simpler solution than the others posted:

(define (dups lst)
    (if (< (length lst) 2)
        ; No room for duplicates
        '()
        ; Check for duplicate at start
        (if (equal? (car lst) (cadr lst))
            ; Starts w/ a duplicate
            (if (or (null? (cddr lst)) ; end of list
                    (not (equal? (car lst) (caddr lst)))) ; non-matching symbol next
                ; End of run of duplicates; add to front of what we find next
                (cons (car lst) (dups (cdr lst)))
                ; Othersise keep looking
                (dups (cdr lst)))
            ; No duplicate at start; keep looking
            (dups (cdr lst)))))

这篇关于打印列表的相邻重复项(方案)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆