Page 1 of 1

Member using MAP

Posted: Mon Dec 19, 2011 2:34 pm
by NickNatra
I must write a function that checks whether an atom is a member of a list not necessarily linear.
This is my piece of code, but it works only for linear lists.
Can anyone see where I'm wrong?

Code: Select all

(defun myor(l)
   (cond
      ((null l) l)
      ((atom l) T)
      ((not (null (car l))) T)
      (T (myor (cdr l)) )
   )
)
 
(defun memberl(e l)
   (cond
      ((and (atom l) (equal e l))  (list T) )
      ((atom l) (list NIL))
      (T (myor (mapcan #'(lambda (l) (memberl e l) ) l ) ))
   )
)
example:
(memberl '1 '(1 2 3 4)) ->T
(memberl '1 (2 3 4)) ->NIL
(memberl '1 '(2 4 5 6 (1 9))) ->NIL (expected: T)

Thanks a lot.

Re: Member using MAP

Posted: Mon Dec 19, 2011 4:10 pm
by Konfusius
Since you made efford to solve the problem yourself (no sane lisp programmer would write the code like you did) i give you a solution.

Code: Select all

(defun deep-member (elm list)
  (or (equal elm list)
	   (deep-member elm (car list))
	   (deep-member elm (cdr list)))
But you have to rewrite the code yourself (using cond etc) because otherwise your professor would become suspicious. No beginner would solve the problem like this.

Re: Member using MAP

Posted: Tue Dec 20, 2011 1:06 am
by NickNatra
The problem is that i have to use MAP functions, like MAPCAN, MAPCON, MAPCAR
and that's the tricky part. :cry:
So, can you give me some more tips please?

Re: Member using MAP

Posted: Wed Dec 21, 2011 1:35 am
by pnathan
a list is a linear datastructure by definition.

therefore I am inferring that you must mean nested lists.

The absolutely lame solution would be to write an implementation of FLATTEN and then work against that. If I was excruciatingly in a hurry and didn't care about the quality of my code and couldn't think of a better way, I would do that.

The clear pointed-at solution is to use recursion.

Here is a partial solution. You will have to figure out reducing the list to a single T or nil. My initial attack was (apply #'or ...) but OR is actually a macro. :) You may find these functions useful - http://www.lispworks.com/documentation/ ... c.htm#some . They aren't common in the Lisp code I've seen so far.

Code: Select all

(defun member-rec (list thingie)
  (mapcar #'(lambda (val)
	      (if (atom val)
		  (eql val thingie)
		  (member-rec val thingie)))
	  list))

Re: Member using MAP

Posted: Wed Dec 21, 2011 1:54 pm
by NickNatra
Thanks for the help