首页 > 解决方案 > 定义 elisp 函数,获取 2 个列表并返回列表 1 中的原子在列表 2 中出现的次数

问题描述

我将如何定义一个接收 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.


推荐阅读