我的程序中有两个函数.注释掉的那个将列表中的每个元素修改为五.第二个函数计算元素在列表中出现的次数.如何将这两者结合起来得到我想要的结果,以确定列表中有多少元素可以被5整除?
这是我的代码:
(defun divide-bye-five (lst)
(loop for x in lst collect (mod x 5)))
(defun counter (a lst)
(cond ((null lst) 0)
((equal a (car lst)) (+ 1 (counter a (cdr lst))))
(t (counter a (cdr lst)))))
(counter '0 '(0 0 0 20 0 0 0 0 0 5 31))
Run Code Online (Sandbox Code Playgroud)
如果你只需要选择列表中的所有元素,可以分为五个,你可以使用remove-if-not
.
(defun dividable-by-5 (num)
(zerop (mod num 5))
CL-USER> (remove-if-not #'dividable-by-5 '(1 2 3 10 15 30 31 40))
(10 15 30 40)
Run Code Online (Sandbox Code Playgroud)
但是我不确定,你想要选择这些元素,还是只计算它们?当然你可以通过调用length
结果列表来计算它们,或者你不需要所有元素,但只需要一个数字,你可以使用count-if
.
CL-USER> (count-if #'dividable-by-5 '(1 2 3 10 15 30 31 40))
4
Run Code Online (Sandbox Code Playgroud)