gpt4 book ai didi

Lisp函数解释

转载 作者:太空宇宙 更新时间:2023-11-03 18:53:48 25 4
gpt4 key购买 nike

我在 LISP 中有这个例子,它从列表的每一层删除给定的数字:

(defun remove_aux (e l)
(cond
((equal e l) nil)
((atom l) (list l))
(t(list(apply 'append (mapcar #'(lambda (l) (remove_aux e l)) l))))))

(defun remove_el (e l)
(car (remove_aux e l)))

所以,如果它像这样运行:(remove_el 2 '(1 2 3 ((2 3 2) 4))) => (1 3 ((3) 4))

我不太明白这一行是如何工作的:(t(list(apply 'append (mapcar #'(lambda (l) (sterge_aux e l)) l))))

如果我有没有列表的行并附加 ((t(mapcar #'(lambda (l) (remove_aux e l)) l))) 结果是 ((1) NIL (3) ((NIL (3) NIL) (4)))) 如果它有附加但没有列表 ( (t(apply 'append (mapcar #'(lambda (l) (remove_aux e l)) l))) ) 然后结果是 (1 3 3 4) 我不明白为什么,因为我做了 (apply 'append '((1 ) NIL (3) ((NIL (3) NIL) (4))))) 在 Common Lisp 控制台中,结果是 ((1 3 (NIL (3) NIL) (4) )) 所以我真的很困惑。有人可以逐步向我解释这一切是如何运作的吗?

最佳答案

我对下面的代码进行了注释,希望能解释发生了什么。您可能会感到困惑,因为 l 在 lambda 中被重新定义...所以 t 行(在您的示例中)有 2 个“l”,但第一个与第二个不同。

(defun remove_aux (e l)
(cond
((equal e l) nil) ;if e equals l return nil
((atom l) (list l)) ;if l is an atom return a list with just l in it
(t ; otherwise...
(list ;create a list
(apply 'append ; whose contents are created by appending
; together the lists that come out of this mapcar
; (apply the append method)
(mapcar #'(lambda (l) ( ; iterate over each of the elements in list l
; the one after the lambda not the one
; being passed to the lambda.
; (this is a horrible name choice
; lambda(l-item) would be much better)
remove_aux e l
; recursively call this method
; with e (which was passed in at the start)
; and l which isn't the l passed in,
; but is an entry of it (see why naming's
; so important?)
; this returns a list
; which will get appended by the append
; with the results of all the other calls
; to remove_aux for each item in the outer l
)
) l)
)))))

(defun remove_el (e l)
(car (remove_aux e l)
)
)

关于Lisp函数解释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20410743/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com