我如何定义一个接受2个列表(l1 l2)的函数,并返回列表1中列表1中的原子出现的次数。
诀窍是迭代第二个列表,计算你遇到的事物中有多少出现在第一个列表中。 member
函数允许您进行该测试,因此您最终可能会选择以下两个选项之一:
;; A version with explicit recursion down the list
;;
;; This will blow its stack if list is too long.
(defun count-known-atoms (known list)
"Return how many of the elements of `list' are atoms and appear
in `known'."
(if (null list)
0
(let ((hd (car list)))
(+ (if (and (atom hd) (member hd known)) 1 0)
(count-known-atoms known (cdr list))))))
;; A version using local variables and side effects. Less pretty, if you're a
;; fan of functional programming, but probably more efficient.
(defun count-known-atoms-1 (known list)
"Return how many of the elements of `list' are atoms and appear
in `known'."
(let ((count 0))
(dolist (x list count)
(when (and (atom x) (member x known))
(setq count (1+ count))))))
;; (count-known-atoms '(1 2) '(0 1 2 3 4 5)) => 2
;; (count-known-atoms-1 '(1 2) '(0 1 '(2) 3 4 5)) => 1
如果ELisp有一个sum
函数来对列表或某种fold
求和,另一种选择是在第二个列表中映射以得到0和1然后然后将它们压缩。我不认为它确实如此,所以我建议count-known-atoms-1
。