2013-10-25 55 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 

請注意,我們只穿過第一個列表,第二個列表仍然通過不斷迭代。

相關問題