Lisp函数解释

标签 lisp common-lisp

我在 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/

相关文章:

lisp - 如何在 quicklisp 中升级 asdf 版本?

Clojure:迭代集合图

vector - 向量的解构

parsing - 在没有所有可用包或加载所有内容的情况下从 lisp 读取/解析常见的 lisp 文件

list - lisp 编程中的变量

list - LISP:仿函数位置的非法参数

C++ 代码和来自 C 的对象?

common-lisp - 如何避免为一个常见的 lisp 项目加载多个 asdf 文件?

common-lisp - 相当于 virtualenv 或 rvm 的 Common Lisp?

emacs - 在没有 ielm 模式的情况下评估 emacs 中的简单 elisp 缓冲区