方案词列表eq? [英] scheme word lists eq?

查看:101
本文介绍了方案词列表eq?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了一个问题:例如,我需要查找列表是否等于第二个列表:

i've got a problem: I need to find if list equal to the second one, for example:

(set%eq? '(1 2 3) '(1 2 3))     ===> #t

(set%eq? '(1 2 3) '(2 3 4))     ===> #f

这些示例在我的程序中是正确的,但是这不是:

That examples are correct in my program, but this one is not:

(set%eq? (quote ((quote one) (quote two) (quote three))) (quote ((quote one) (quote two) 
(quote three))))    ====> #f but i need #t

怎么了? 这是我的程序:

what's wrong? this is my program:

(define (set-eq? xs ys) 

(cond ((and (null? xs) (null? ys)) #t) 
       ((null? ys) #f) 
       ((eq? (car xs) (car ys)) (set-eq? (cdr xs) (cdr ys)))
       ((eq? (car xs) (car (reverse ys))) (set-eq? (cdr xs) (cdr (reverse ys))))
       (else #f)))

推荐答案

所发布的代码中有几个错误,仅供参考,该过程测试两个 lists 是否相等,不是真的测试两个之间的相等性:

There are a couple of mistakes in the posted code, and FYI, the procedure tests whether two lists are equal, it's not really testing for equality between two sets:

(define (set-eq? xs ys)
  (cond ((and (null? xs) (null? ys)) #t)
        ((or (null? xs) (null? ys))  #f) ; missing case
        ((equal? (car xs) (car ys)) (set-eq? (cdr xs) (cdr ys))) ; use equal?
        ; deleted unnecessary case here. Anyway, why are you reversing the list?
        (else #f)))

现在这将起作用:

(set-eq? '(1 2 3) '(1 2 3))
=> #t

(set-eq? '(1 2 3) '(2 3 4))
=> #f

(set-eq? (quote ((quote one) (quote two) (quote three)))
         (quote ((quote one) (quote two) (quote three))))
=> #t

实际上,这也可以工作:

In fact, this will work, too:

(equal? '(1 2 3) '(1 2 3))
=> #t

(equal? '(1 2 3) '(2 3 4))
=> #f

(equal? (quote ((quote one) (quote two) (quote three)))
        (quote ((quote one) (quote two) (quote three))))
=> #t

...但是这行不通,列表明显不同:

...But this won't work, the lists are clearly different:

(set-eq? '(1 2 3 4) '(4 1 2 3)) 
=> #f

如果要测试两个之间的相等性,则必须完全重新考虑该算法.这是一个主意:编写一个subset?过程,测试一个列表是否是另一个列表的子集(也就是说:如果一个列表中的所有元素都包含在另一个列表中),然后测试(and (subset? l1 l2) (subset? l2 l1))是否为真,如果发生这种情况,那么根据相等的 set 定义,它们是相等的.

If you intended to test for equality between two sets, you have to completely rethink the algorithm. Here's an idea: write asubset? procedure that tests if a list is a subset of another list (that is: if all the elements in one list are contained in the other list), and then test whether (and (subset? l1 l2) (subset? l2 l1)) is true, if that happens, then they're equal according to the set definition of equality.

这篇关于方案词列表eq?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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