math - LISP 中的计数器变量

标签 math lisp common-lisp

定义函数“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/

相关文章:

algorithm - 使用乘法实现加法

python - 带有移位孔的环形空间内的随机点

python - 使用 Lambdas 从字符串表达式构建可执行函数

excel - 需要帮助调试 LISP 脚本错误/八位字节序列 141

common-lisp - 普通口齿不清 : Undefined function k

sockets - Clozure Common Lisp 中的 make-socket 错误

C++整数层函数

lisp - CLOS 插槽访问器 : read but not write

scala - 无法使用静态语言创建应用函数?

macros - 通用Lisp递归宏扩展