代码之家  ›  专栏  ›  技术社区  ›  ObiJuanKanobe

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

  •  1
  • ObiJuanKanobe  · 技术社区  · 10 年前

    我的程序有两个功能。被注释掉的元素将列表中的每个元素修改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 回复  |  直到 10 年前
        1
  •  5
  •   Rainer Joswig mmmmmm    10 年前

    如果您只需要选择列表中的所有元素,这些元素可以除以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
    
        2
  •  1
  •   Sylwester    10 年前

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

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