count - 如何计算 lisp 列表中出现的次数

标签 count lisp common-lisp sublist

任务是

count-of (symbol list) Write a function named count-of that takes two parameters, a symbol and a list. Count the number of instances of x in the list. Do not count the number of x in any sub-lists within the list.

我不知道如何跳过测试列表中的子列表。他使用的是字母而不是数字,所以我不能使用 numberp,而当我只有一个字母时我不能使用 list-length。我也不确定我是否正确地执行了 let* 然后 setf 但我无法以任何其他方式让它工作。

(defun count-of (x list)
  (let* count 0)
  (setf count 0)
  (dolist (y list)
    (if (not a sublist) 
        (setf count (+ count 1)))))

(print (count-of 'a '(a '(a c) d c a)))

最佳答案

I can't figure out how to skip over the sublist in the test list.

为了检查子列表,您必须做更多 工作,因此作业实际上是要求您保持简单。考虑到您可以使用 EQL 非递归地比较值:

(eql 'a 'b) => NIL
(eql 'a 'a) => T

但是 eql 不限于符号和数字,您可以传递任何对象,当两个值不完全相等时它将返回 NIL。

(eql '(a b c) 'a) => NIL

换句话说,当您找到与 eql 的匹配项时,您的计数器就会增加,仅此而已。

He is using letters not numbers so I can't use numberp, and when I just have one letter I can't use list-length.

如果您想区分符号和列表,可以使用谓词,例如 atomconsp,甚至 typecase (参见 14.2 The Conses Dictionary )。

Also I am not sure I and doing the let* then setf correctly but I can't get it to work any other way.

你确实用错了letLET在主体周围引入变量,例如:

(let ((x 10)
      (y 20))
  (+ x y))

所以你需要做:

(let ((count 0))
  (dolist (x list count)
    ...))

请注意 DOLIST接受第三个参数,该参数是将在循环结束时计算的形式。在循环内,您可以根据需要setf 进行计数(另请参阅incf)。

关于count - 如何计算 lisp 列表中出现的次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58159766/

相关文章:

c - 字符串计数器的词频有时会出错

lisp - GNU Common Lisp(类型)的详细信息

regex - 我应该在 Common Lisp 中使用哪些正则表达式库?

mysql - 计数(*)+分组依据+有

php - 使用 PHP 返回文件夹内的文件总数

lisp - 我正在尝试从 LISP 中的列表中删除/清除所有重复出现的术语

scheme - "map"是否一定会产生额外的嵌套级别?

common-lisp - 发生错误时如何使Clozure退出

常见的 lisp、CFFI 和实例化 c 结构

mysql - 从 Xoops 数据库中计算并插入评论