user2899108
user2899108

Reputation: 45

Lisp: Difference of List2 to List1

I am fairly new to lisp and trying to breakdown this problem with getting the difference of two lists. I need to find all the numbers in list 2 that are not in list 1

Looking to get (diff list1 list2)...Example would be that (diff '(4 5 6 8 9) '(1 2 4 6 8 9)) Return would be (1 2)

What I have so far

(defun diff (l1 l2) 
  (cond ((null l1) nil) 
        ((member (first l1) l2) (diff(rest l1) l2)) 
        (t (cons (first l2) (diff (rest l2) l1)))))


(defun diff1 (l1 l2)
  (cond ((null l1) nil) 
        ((member (first l2) l1) (diff (rest l2) l1)) 
        (t (cons (first l2) (diff (rest l2) l1)))))

These are two different methods I have tried but cannot seem to get it return List 2 over list 1.

Upvotes: 3

Views: 921

Answers (1)

sds
sds

Reputation: 60014

You have a typo in the last line of diff:

(defun diff (l1 l2)
  (cond ((null l2) nil) 
        ((member (first l2) l1) (diff l1 (rest l2))) 
        (t (cons (first l2) (diff l1 (rest l2))))))

Note that the bug is obvious once you format your code properly :-)

Also, the function you are looking for is already present in Common Lisp under the name set-difference.

Upvotes: 4

Related Questions