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

时间:2016-03-16 22:03:25

标签: lisp common-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))

2 个答案:

答案 0 :(得分: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)

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

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

答案 1 :(得分:1)

如果你有两个函数,其中一个的结果是你想要的第二个输入你可以像这样组合它们:

(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)))