我的替换功能有问题

use*_*198 2 emacs replace elisp

我试图将一个简单的替换方法作为一个新的Lisp用户,但无法理解为什么这不能正常工作.

;replace element e1 with element e2 in a list L
(defun my-replace (e1 e2 L)
  (cond
   ;if the first of L is e1, cons e2 & rest L 
   ((equal (car L) (e1)) (cons (e2) (my-replace (e1 e2 (cdr L)))))
   ;else cons e1 & rest L
   (t  (cons (e1) (my-replace (e1 e2 (cdr L)))))))
Run Code Online (Sandbox Code Playgroud)

jla*_*ahd 6

您的代码中存在几个问题.首先,你有一些额外的括号.e1表示值的值e1,但(e1)表示函数的返回值e1.由于你没有这样的功能,它将失败.

此外,您的循环缺少终止条件.就像现在一样,在第一个问题得到解决的情况下,它将无限期地运行,总是采用第二个分支并以nilas 递归方式调用自身L.

最后,cons后一个分支的第一个参数是错误的:当(car L)不匹配时e1,你想要构建结果(car L)而不是e1,对吗?这是保留列表中的内容,而不是用第一个参数替换它.

这是固定版本:

(defun my-replace (e1 e2 L)
  (cond
    ;;if at the end of list, terminate
    ((null L) nil)
    ;;if the first of L is e1, cons e2 & rest L 
    ((equal (car L) e1)
     (cons e2 (my-replace e1 e2 (cdr L))))
    ;;else cons e1 & rest L
    (t
     (cons (car L) (my-replace e1 e2 (cdr L))))))
Run Code Online (Sandbox Code Playgroud)