【发布时间】:2019-04-23 17:03:45
【问题描述】:
我将如何定义一个接收 2 个列表 (l1 l2) 并返回列表 1 中的原子在列表 2 中出现的次数的函数。
【问题讨论】:
-
这个问题可以帮助你获得大部分的成功:stackoverflow.com/questions/6050033/elegant-way-to-count-items
标签: elisp
我将如何定义一个接收 2 个列表 (l1 l2) 并返回列表 1 中的原子在列表 2 中出现的次数的函数。
【问题讨论】:
标签: elisp
诀窍是遍历第二个列表,计算你遇到的有多少出现在第一个列表中。 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,则另一种选择是映射第二个列表以获取零和一,然后将它们压扁。不过,我认为不会,所以我建议count-known-atoms-1。
【讨论】: