2013-10-25 104 views
0

嗨我想编写一个简单的函数,其中包含2个列表并返回第一个列表中不包含在另一个列表中的元素。从列表中返回元素不包含到另一个列表

例如L1 '(1 2 3 4)L2'(5 6 2 8 3)

返回应该是“(4:1)

目前,我有这样的代码:

(define (iteration2) 
    (define listA '()) 
    (for ([list1 a]) 
     (for ([list2 b]) 
      (if (equal? list1 list2) 
       '() 
       (cons list1 listA)))) 
    listA) 

感谢

+0

首先我试图做到这一点递归但没有成功..然后我试图与2“循环”做出来,本地列表水木清华这样的.. – dionysosz

+0

(定义(迭代2) (定义listA的' ()) (对于([list1进行]) (对于([列表2 b]) (如果(等于list1的列表2) ; “() (利弊list1的listA的) ))) listA ) – dionysosz

+0

人们会更多可能会帮助你,如果你张贴代码。即使代码不起作用。这样我们可以帮助您改进代码,而不是从头开始编写解决方案。编辑:你打败了我。 – axblount

回答

2

之前编写循环(或递归),它总是最好看的内置的功能,可以为你做的循环。在你的情况,你想过滤列表,以便:

(define (first-not-second l1 l2) 
    (filter 
    (lambda (x) (not (member x l2))) 
    l1)) 

(first-not-second '(1 2 3 4) '(5 6 2 8 3)) 
=> '(1 4) 

球拍for版本将

(define (first-not-second l1 l2) 
    (for/list ((x l1) #:unless (member x l2)) 
    x)) 

和经典的 “辅助函数式”给

(define (first-not-second l1 l2) 

    (define (first-not-second-helper l1 l2) 
    (if (empty? l1) 
     '() 
     (let ((x (car l1))) 
      (if (member x l2) 
       (first-not-second-helper (cdr l1) l2) 
       (cons x (first-not-second-helper (cdr l1) l2)))))) 

    (first-not-second-helper l1 l2)) 

在任何情况下,您都不需要遍历第二个列表,因为您可以使用内置的member过程。

+0

哇..正是我在找... ....非常感谢你的朋友! 我是新的计划我不知道大部分内置功能! 我尝试了第一个,它的运行就像一个魅力。 再次感谢... – dionysosz

1

该过程执行列表的差异操作时,将此视为一组差异很有用。诀窍是使用member来确定元素是否在列表中。我将不给予直接的答案杀风景了你,只是填写了空白在这个骨架的解决方案:

(define (diff l1 l2) 
    (cond (<???> ; if the 1st list is empty 
     <???>) ; then we're done building the answer, return the empty list 
     (<???> ; if the 1st list's current element is not a member of 2nd list 
     (cons <???>    ; then cons the 1st list's current element 
       (diff <???> l2))) ; and advance the recursion 
     (else     ; otherwise 
     (diff <???> l2))))  ; just advance the recursion 

请注意,我们只穿过第一个列表,第二个列表仍然通过不断迭代。

相关问题