Member using MAP

Discussion of Common Lisp

Member using MAP

Postby NickNatra » Mon Dec 19, 2011 2:34 pm

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.
NickNatra
 
Posts: 8
Joined: Mon Dec 05, 2011 10:18 am

Re: Member using MAP

Postby Konfusius » Mon Dec 19, 2011 4:10 pm

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.
Konfusius
 
Posts: 62
Joined: Fri Jun 10, 2011 6:38 am

Re: Member using MAP

Postby NickNatra » Tue Dec 20, 2011 1:06 am

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?
NickNatra
 
Posts: 8
Joined: Mon Dec 05, 2011 10:18 am

Re: Member using MAP

Postby pnathan » Wed Dec 21, 2011 1:35 am

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))
pnathan
 
Posts: 1
Joined: Wed Dec 21, 2011 1:18 am

Re: Member using MAP

Postby NickNatra » Wed Dec 21, 2011 1:54 pm

Thanks for the help
NickNatra
 
Posts: 8
Joined: Mon Dec 05, 2011 10:18 am


Return to Common Lisp

Who is online

Users browsing this forum: Bing [Bot] and 4 guests