Page 1 of 1

print same elements in two lists

PostPosted: Thu Oct 15, 2015 12:19 pm
by lispstudent
I've been trying to write a lisp code that prints intersecting elements. But there is a exception. It can be nested list. Below you can see expected and gotten output.

Code: Select all
Gotten output:
> (intersect '(a b c) '( b a c))
a b c
>(intersect '(a (b c) d) '(a b c d))
a d
>(intersect  '(a b (c f)) '(a d (c f) e) )
a


Code: Select all
Expected output:
> (intersect '(a b c) '( b a c))
a b c
>(intersect '(a (b c) d) '(a b c d))
a d
>(intersect  '(a b (c f)) '(a d (c f) e) )
a (cf)


As you see, if there are two same lists in the lists it should be printed. If there are same elements in two lists but one and more often in other list in list, it shouldn't be printed as you see in the second. How can I get the expected output? Could you fix my code:

Code: Select all
(defun printelems  (A B)
  (if (eq A ())
      A
      (if (member (first A) B)
          (cons (first A) (printelems (rest A) B))
          (printelems (rest A) B))))

Re: print same elements in two lists

PostPosted: Fri Oct 16, 2015 9:22 pm
by nuntius
The default test used by member doesn't check list equality.
You need to pass a different :test to the member function.

http://www.lispworks.com/documentation/ ... _mem_m.htm