I want to test for equality amongst lists, but 开发者_开发知识库I really only care that the members are the same, not the ordering. Are there any simple operators to check for this?
A rather trivial example
(my-equal? (a b) (b a))
Should return #t.
Obviously, this particular example can easily be done by checking for both lists and then reversing the second and checking again
(or (equal? (a b) (b a)) (equal? (a b) (reverse (b a)))
But is there a way in general? I could have a stab at writing a function but I can only imagine something quite complicated that would do the work. I am guessing this must be a fairly common need and I wonder if scheme has an operator in-built that can do the work here.
I am using mit-scheme 9.0.1
If your implementation has SRFI 1 available, there is lset=
to achieve what you want:
Set operations on lists
If you were using Racket, I would point you to this page, with built-in support for sets.
No, that's not answering your question, I know.
Or if you want to do it old-school, you can just write a few little functions.
I sincerely hope you are not using this for homework.
(define (unordered-union-set set1 set2)
(cond ((null? set2) set1)
(else
(if (in-set? (car set2) set1)
(unordered-union-set set1 (cdr set2))
(cons (car set2) (unordered-union-set (cdr set2) set1))))))
(define (in-set? item set)
(cond ((null? set) #f)
((equal? item (car set)) #t)
(else (in-set? item (cdr set)))))
(define (set-equal? set1 set2)
(if (equal? (length set1) (length set2))
(if (equal? (length set1) (length (unordered-union-set set1 set2)))
#t
#f)
#f))
Use set-equal? on any two sets.
This works based on some simple set theory. If the union of the two sets of equivalent cardinality, yields a set with a cardinality equivalent to the cardinality of the first or last set, the sets are equivalent.
My point in writing this is to say that there is no simple operator for this, but a long complicated procedure is not necessary if you use the set union trick.
My implementation doesn't have SRFI 1, but I highly doubt lset= will be any faster than this function.
But now that I read your comments, you need it to be valid for '(1 1 2) and '(2 1). Since these are not sets, this method will not work, but not hard to implement. So, in fact, this procedure is equivalent to lset=.
精彩评论