任务是
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.
如果您想区分符号和列表,可以使用谓词,例如 atom
或 consp
,甚至 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.
你确实用错了let
; LET
在主体周围引入变量,例如:
(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/