LISP中的计数器变量 [英] Counter variable in LISP

查看:171
本文介绍了LISP中的计数器变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

定义函数"occ",该函数采用列表L和符号A,并计算L中符号A的出现. 例子: (occ'((((s)o)d)'f)-> 0

Define the function 'occ' that takes a list L and a symbol A and counts the occurance of symbol A in L. Example: (occ '(((s) o ) d) 'f) --> 0

到目前为止我所得到的:

What i have gotten so far:

(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的任何更高功能.

However My output keep saying Nil instead of displaying the counter value. I cannot use any higher-functions of LISP.

推荐答案

首先,不要在您的函数内部使用setq进行变量初始化,请使用let.其次,让我们看看为什么您做错了,您的代码:

First of all, don't use setq for variable initialization inside yout function, use let. Second, let's look why you doing it wrong, your code:

(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)))))

无论如何,您不需要任何计数器变量即可完成所需的操作.

Anyway, you don't need any counter variables to do what you want.

右边的函数可能看起来像这样(我更改了参数顺序,因为对我来说在LIST中找到SYMBOL看起来更好)

Right function may look like this (i changed arguments order becaus it looks better for me to find SYMBOL in LIST):

(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

这篇关于LISP中的计数器变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆