This is a read-only archive of lispforum.com. The forum was locked to new users and posts and is preserved here as static HTML from a database snapshot taken on 2019-09-07.

Recursive 'member-of'

3 posts · 2327 views

I'm trying to write a 'member-of' function, to check whether an element is a member of a list or not.

My first attempt, the iterative one, is pretty easy:
(defun member-of (elem the-list)
  (if (eql elem (car (member elem the-list)))
	'T
	'NIL)
Now I want to make the recursive version.
(defun member-of (elem the-list)
  (if (eql elem (car the-list))
	'T
	(member-of elem (cdr the-list))))
Of course that only works if the element is indeed a member of the list.
If the element isn't, this function will not terminate.
How to fix this? :?

Re: Recursive 'member-of'

also terminate when the list is empty? and your "iterative" version doesn't really count; it just wraps (oddly) a preexisting function. and don't quote T or NIL.

I would try using DOLIST to write a proper iterative version. Then the recursive version should be straightforward.

Re: Recursive 'member-of'

anta40 wrote:
(defun member-of (elem the-list)
  (if (eql elem (car the-list))
	'T
	(member-of elem (cdr the-list))))
Of course that only works if the element is indeed a member of the list.
If the element isn't, this function will not terminate.
How to fix this? :?
The problem is that when you get to the end of the list, you call:
(member-of elem (cdr '(last-elem)))
where (cdr '(last-elem)) returns NIL.

Then you test (eql elem (car NIL)), but (car NIL) is NIL and (eql elem NIL) is false, so you get down to:
(member-of elem (cdr NIL))
But (cdr NIL) is also NIL (just as (cdr '(last-elem)) is NIL), so you get into an infinite loop.

As nuntius said, you need to check first to see if the list is empty before doing the other checks.

By the way, your first version could be written like this:
(defun member-of (elem the-list)
  (when (member elem the-list)
    t))