`(disivible「(1 2 3 4 5 6 7))這是我到目前爲止已經取得:Lisp的整除
(defun divisible(n)
(cond ((eq n 0) nill) (eq(rem n 3) 0) t)('else 0)))
但我在口齒不清新的,我不知道如何讓它不顯示我可以被3整除的數字,但只需添加數字並顯示結果。有人能幫助我嗎?
`(disivible「(1 2 3 4 5 6 7))這是我到目前爲止已經取得:Lisp的整除
(defun divisible(n)
(cond ((eq n 0) nill) (eq(rem n 3) 0) t)('else 0)))
但我在口齒不清新的,我不知道如何讓它不顯示我可以被3整除的數字,但只需添加數字並顯示結果。有人能幫助我嗎?
過濾remove-if-not
和應用+
(defun divisible (num-list)
(apply #'+ (remove-if-not #'(lambda(x)(zerop (rem x 3))) num-list)))
由於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)))
(defun divisible (num-list)
(reduce #'+
(remove-if-not #'zerop
num-list
:key (lambda (x)
(mod x 3)))))
在計劃,與[SRFI 26](http://srfi.schemers.org/srfi-26/srfi-26.html),你可以寫lambda as'(cut mod <> 3)'。有人應該在CL中編寫一個等效的宏。 ;-) –
@Chris Jester-Young:打電話給我老式的,但我更喜歡簡單的LAMBDA,而不僅僅是函數的另一個語法以及如何調用它們。用宏改進功能語法也不合適。我認爲這暴露了糟糕的風格(用略有不同的東西替換核心Lisp),並且不利於可維護的軟件。它以一種自我挫敗的方式聰明。 –
(defun sum3s (x) (loop for i in x :if (= (mod i 3) 0) :sum i))
這是上述答案的另一變型。
請勿使用APPLY。使用REDUCE。應用是將參數作爲列表應用於功能。參數列表有一個可能的小長度限制。 REDUCE用於從任意長列表中計算一個值。 –