如何创建可以从列表中查找值的关联函数。 任何人都可以帮助我,因为我不知道它是如何工作的,并且是lisp的新手。 你能分步说明吗? 我已经开始搜索它了,但是在创建关联函数时找不到任何东西。
答案 0 :(得分:2)
最基本的lisp操作是食客:
(defun some-function (list-to-consume perhaps-additional-args)
(cond ((endp list-to-consume) <end-of-list-expression>)
((<predicate> list-to-consume perhaps-additional-args)
<result-expression>)
(t (some-function (cdr list-to-consume) perhaps-additional-args))))
示例:
;; The predicate is the endp expression
(defun mylength (list &optional (len 0))
(cond ((endp list) len)
(t (mylength (cdr list) (1+ len)))))
;; A member function
(defun mymember (element list)
(cond ((endp list) nil)
((equal (car list) element) list)
(t (mymember element (cdr list)))))
;; Exchange an element with another in a list
;; notice how this builds up a list recursively
(defun exchange (list element replacement)
(cond ((endp list) nil)
((equal (car list) element) (cons replacement (exchange (cdr list) element replacement)))
(t (cons (car list) (exchange (cdr list) element replacement)))))
还有其他更高级的方法可以使用loop
或更高阶函数(例如mapcar
,map
和reduce
)替换大多数食客,但如果您正在学习LISP,可能应该先熟悉一下食客。