在 LISP 中如何检查列表中的哪些元素可以被 5 整除?

How do I check what elements in a list are divisible by five in LISP?

我的程序中有两个函数。被注释掉的那个将列表中的每个元素修改为 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))

如果您只需要 select 列表中可被 5 整除的所有元素,您可以使用 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)

但我不确定,你想要 select 这个元素,还是只计算它们?当然,您可以通过在结果列表上调用 length 来计算它们,或者您不需要所有元素,而只需要一个数字,您可以使用 count-if.

CL-USER> (count-if #'dividable-by-5 '(1 2 3 10 15 30 31 40)) 
4

如果您有两个函数,其中一个函数的结果是您希望作为第二个函数的输入,您可以像这样组合它们:

(second-fun (first-fun first-fun-arg ...))

所以特别是使用您提供的功能应该可以做到:

(counter 0 (divide-bye-five '(1 2 3 4 5 6 7 8 9 10))) ; ==> 2

如果您想将其抽象化,您可以将其设为函数:

(defun count-dividable-with-five (lst)
  (counter 0 (divide-bye-five lst)))