Scheme 检查方案中的排列
我需要在一个方案中编写一个函数,该方案接受两个列表,如果其中一个列表是另一个列表的排列,则返回trueScheme 检查方案中的排列,scheme,permutation,Scheme,Permutation,我需要在一个方案中编写一个函数,该方案接受两个列表,如果其中一个列表是另一个列表的排列,则返回true 例如 (置换(347)-(734))将返回#t (置换“(347)”(C3445))将返回#f 这是我到目前为止得到的代码,但我被卡住了: (define (permutation list1 list2) (cond ((equal? list1 list2)) ((not (list? list1))) ((memq (car list1) list2) (p
例如
(置换(347)-(734))
将返回#t(置换“(347)”(C3445))
将返回#f
这是我到目前为止得到的代码,但我被卡住了:
(define (permutation list1 list2)
(cond
((equal? list1 list2))
((not (list? list1)))
((memq (car list1) list2) (permutation (cdr list1) list2))
(else #f)
))
谢谢当且仅当
- 从
中删除list2
的元素将生成空列表,并且list1
- 从
中删除list1
的元素会生成空列表list2
(define (permutation? xs ys)
(and (empty? (without xs ys))
(empty? (without ys xs))))
假设您有一个函数remove first
,用于从列表中删除元素的第一个实例,您可以使用折叠定义,而不使用:
(define (without xs ys)
(foldl (lambda (x ls) (remove-first x ls)) ys xs))
剩下的就是先删除:
(define (remove-first x xs)
(cond ((empty? xs) '())
((equal? x (first xs)) (rest xs))
(else (cons (first xs) (remove-first x (rest xs))))))
(在您的方案中,remove first
可能已经作为remove
提供)您可以轻松地对每个列表进行排序并按元素进行比较。看看这个问题的答案