Lisp可分性

时间:2013-12-15 13:36:18

标签: lisp common-lisp

`(disivible'(1 2 3 4 5 6 7))。这是我到目前为止所做的:

(defun divisible(n)
    (cond ((eq n 0) nill) (eq(rem n 3) 0) t )('else 0)))

但我是lisp的新手,我不知道如何让它不显示3可被整除的数字,只需添加数字并显示结果。有人能帮帮我吗?

3 个答案:

答案 0 :(得分:4)

由于apply可能不适用于长列表,因此这里是loop版本:

(defun divisible (lst)
  (loop for i in lst when (zerop (rem i 3)) sum i))

或使用reduce

(defun divisible (lst)
  (reduce '+ lst :key (lambda (i) (if (zerop (rem i 3)) i 0))))

递归版

(defun divisible (lst)
  (if (null lst)
    0
    (let ((i (car lst)))       
      (if (zerop (rem i 3))
        (+ i (divisible (cdr lst)))
        (divisible (cdr lst))))))

或更笨拙的尾递归版

(defun divisible (lst)
  (labels 
      ((sub (lst res)
         (if (null lst)
           res
           (let ((i (car lst)))
             (sub 
              (cdr lst) 
              (if (zerop (rem i 3)) (+ i res) res))))))
    (sub lst 0)))

答案 1 :(得分:1)

(defun sum3s (x) (loop for i in x :if (= (mod i 3) 0) :sum i))

这是上述答案的另一种变体。

答案 2 :(得分:0)

过滤remove-if-not并应用+

(defun divisible (num-list)
  (apply #'+ (remove-if-not #'(lambda(x)(zerop (rem x 3))) num-list)))