【问题标题】:Define elisp function, takes 2 lists and returns number of times atom in list 1 occurs in list 2定义 elisp 函数,获取 2 个列表并返回列表 1 中的原子在列表 2 中出现的次数
【发布时间】:2019-04-23 17:03:45
【问题描述】:

我将如何定义一个接收 2 个列表 (l1 l2) 并返回列表 1 中的原子在列表 2 中出现的次数的函数。

【问题讨论】:

标签: elisp


【解决方案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,则另一种选择是映射第二个列表以获取零和一,然后将它们压扁。不过,我认为不会,所以我建议count-known-atoms-1

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-10-22
    • 1970-01-01
    • 2021-09-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多