定义函数“occ”,它接受一个列表 L 和一个符号 A,并计算符号 A 在 L 中的出现次数。 例子: (occ '(((s) o ) d) 'f) --> 0
到目前为止我得到了什么:
(defun occ(list a)
(setq counter 0)
;Checks if the given list is has an nested list
(if (consp list)
; Breaking the list down atom by atom and recursing
(or (occ a (car list))
(occ a (cdr list)))
; checks if symbols are the same
(if(eq a list)
(setq counter(1+ counter)))))
但是我的输出一直显示 Nil 而不是显示计数器值。 我不能使用 LISP 的任何高级功能。
最佳答案
首先,不要在yout函数中使用setq进行变量初始化,使用let
。其次,让我们看看你为什么做错了,你的代码:
(defun occ(list a)
(setq counter 0) ;; You always setting counter to 0 on new
;; level of recursion
(if (consp list)
(or (occ a (car list)) ;; You reversed arguments order?
(occ a (cdr list))) ;; according to your definition it must be
;; (occ (car list) a)
(if(eq a list)
(setq counter(1+ counter)))))
无论如何,您不需要任何计数器变量来执行您想要的操作。
正确的函数可能看起来像这样(我改变了参数顺序因为在 LIST 中找到 SYMBOL 对我来说看起来更好):
(defun occ (sym nested-list)
(cond
((consp nested-list)
(+ (occ sym (car nested-list)) (occ sym (cdr nested-list))))
((eq sym nested-list) 1)
(t 0)))
CL-USER> (occ 'x '(((s) o ((f ()) f)) d))
0
CL-USER> (occ 'f '(((s) o ((f (x (((f))))) f)) d f))
4
关于math - LISP 中的计数器变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26705229/