Scheme Function to remove one list's items from another
I'm trying to create a scheme function wh开发者_如何学Goich given two lists L1 and L2, will remove any items present in L2 from L1.
I have a small start, but I don't know exactly what else to do.
(define (remove L1 L2)
(((null? L2) L1))
Here is a code snippet for the simple case.
(define (remove L1 L2)
(cond ((null? L1) '())
((memv (car L1) L2) (remove (cdr L1) L2))
(else (cons (car L1) (remove (cdr L1) L2)))))
Remember that in Scheme, or any functional language, the question you need to ask is not "what should I be doing?", but rather you should ask "what value do I need to produce?".
Please note that this simple example doesn't handle nested lists. So (remove '(A (C D)) '(B C D))
would produce (A (C D))
. Handling nesting lists is left as an exercise for the reader :D
You can simply use SRFI 1's lset-difference
:
(lset-difference = '(1 2 3 4 5) '(3 4 5 5 6))
; => (1 2)
The =
, in my example, is the comparison function. If your lists contain strings, say, instead of numbers, then you should use string=?
in place of =
.
精彩评论