anta40 wrote:Code: Select all
(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:
Code: Select all
(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:
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:
Code: Select all
(defun member-of (elem the-list)
(when (member elem the-list)
t))