print same elements in two lists

You have problems, and we're glad to hear them. Explain the problem, what you have tried, and where you got stuck.
Feel free to share a little info on yourself and the course.
Forum rules
Please respect your teacher's guidelines. Homework is a learning tool. If we just post answers, we aren't actually helping. When you post questions, be sure to show what you have tried or what you don't understand.
Post Reply
lispstudent
Posts: 3
Joined: Thu Oct 15, 2015 12:11 pm

print same elements in two lists

Post by lispstudent » Thu Oct 15, 2015 12:19 pm

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))))

nuntius
Posts: 538
Joined: Sat Aug 09, 2008 10:44 am
Location: Newton, MA

Re: print same elements in two lists

Post by nuntius » Fri Oct 16, 2015 9:22 pm

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

Post Reply