3 ms·
My idea for teaching it is to start with just a function that calls the library function: (defun our-member (item list) (cond (t (member item li
by aidenn0 9y ago
My idea for teaching it is to start with just a function that calls the library function:
(defun our-member (item list)
(cond
(t (member item list))))
Now everyone in the class should quickly agree that this function works. Next say "our goal is to write our own implementation of member, so we will handle one special case at a time until we don't need to call member anymore"
so step 1:
(defun our-member (item list)
(cond
((atom list) nil) ;; if it's not a non-empty list, it can't be a list containing item
(t (member item (cdr list)))))
step 2:
(defun our-member (item list)
(cond
((atom list) nil) ;; if it's not a non-empty list, it can't be a list containing item
((eql (car list) item) list) ;; if the first element of the list is our item,
;; we have a match and return the whole list
(t (member item list))))
step 3:
(defun our-member (item list)
(cond
((atom list) nil) ;; if it's not a non-empty list, it can't be a list containing item
((eql (car list) item) list) ;; if the first element of the list is our item,
;; we have a match and return the whole list
(t (member item (cdr list))))) ;; we already know that the first item is not a match, so we can just run
;; member on the tail of the list
And now demonstrate that replacing member with our-member will still be correct.
[edit]
derp (atom nil) => T