LISP中的计数器变量

编程入门 行业动态 更新时间:2024-10-20 09:32:54
本文介绍了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中的计数器变量

本文发布于:2023-11-22 06:44:19,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1616366.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:变量   计数器   LISP

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!