我正在做一个程序,它接受一个列表和两个原子,如果 atom-1 出现在列表中,则将 atom-1 替换为 atom-2。
我正在使用 Ubuntu 系统在文本编辑器中进行编程
下面是我的代码:
#! /usr/bin/clisp
(defun my-replace (lst x y)
(cond
((eq lst nil) nil)
((eq (cdr lst) nil) nil)
((eq (car lst) x) (setq (car lst) y))
( t (my-replace ((cdr lst) x y)))))
当我尝试执行此操作时,Clisp 显示此错误:
*** - SYSTEM::%EXPAND-FORM: (CDR LST) 应该是一个 lambda 表达式
我是 Lisp 初学者。
请告诉我如何解决这个错误。
最佳答案
首先你应该改进格式和缩进:
(defun my-replace (lst x y)
(cond
((eq lst nil) nil)
((eq (cdr lst) nil) nil)
((eq (car lst) x) (setq (car lst) y))
(t (my-replace ((cdr lst) x y)))))
让我们看一下代码:
(defun my-replace (lst x y)
; in Common Lisp you can write LIST instead of LST
; what are x and y? The naming is not very speaking.
(cond
((eq lst nil) nil)
((eq (cdr lst) nil) nil) ; why this clause?
((eq (car lst) x) (setq (car lst) y))
; instead of SETQ use SETF
(t (my-replace ((cdr lst) x y)))))
; here is a function call? why the extra parentheses
我会首先关注一个非破坏性的版本。您尝试编写一个破坏性修改列表的版本。不。创建一个完成替换的新列表。
如果你想写一个破坏性的版本,你可以这样做,但首先要把基础做好。
关于recursion - 普通口齿不清 : error "CDR LST should be a lambda expression",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32736039/