elisp - 定义 elisp 函数,获取 2 个列表并返回列表 1 中的原子在列表 2 中出现的次数
问题描述
我将如何定义一个接收 2 个列表(l1 l2)并返回列表 1 中的原子在列表 2 中出现的次数的函数。
解决方案
诀窍是遍历第二个列表,计算你遇到的有多少出现在第一个列表中。该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
.
推荐阅读
- python - 当您知道文件的类型但不知道名称时,如何从 Azure Data Lake 下载文件?
- java - 如何在android的Recyclerview中停止GIF图像的动画
- sql - Sqlite 查询:每个播客的最近五集
- python - 计算熊猫系列中连续的个数
- html - Angular不渲染从组件中提取的HTML?
- javascript - 在 React Native 中使用来自 API 的数据进行条件渲染
- java - java.io.FileNotFoundException(没有这样的文件或目录) - 下载文件
- typescript - React Native 仍然使用错误定义的类型(TypeScript)运行
- html - 如何在网页部分内的html部分内显示元素?
- swift - insertSubview() 覆盖整个 Mainview,即使在 0 处插入