gpt4 book ai didi

LISP 过滤函数

转载 作者:太空宇宙 更新时间:2023-11-03 18:53:22 24 4
gpt4 key购买 nike

我必须定义一个函数 filter ,它有一个谓词和一个列表作为参数,并返回初始列表作为值,其中只有满足初始谓词的原子 - 对于每个深度级别 -保持关注 NIL 值以维护列表结构)。

例子:

(filter 'evenp '(24 5 (7) d (((4))) 3 ()))

(24 () (((4))) ())

我想的代码是这样的:

(defun filter (pred list)
(cond ((null list) nil)
((funcall pred (car list))
(cons (car list)
(filter pred (cdr list))))
(T (filter pred (cdr list)))))

我如何实现深度事实,同时保持示例中显示的圆括号?

谢谢大家

最佳答案

这是一个可能的解决方案:

(defun filter (predicate x)
(if (consp x) ; if x is a cons, that is a tree:
(let ((ca (car x))
(cd (filter predicate (cdr x)))) ; filter always the cdr
(if (listp ca) ; if the car of x is a list (nil or cons)
(cons (filter predicate ca) cd) ; then filter also the car
(if (funcall predicate ca) (cons ca cd) cd))) ; car is a non-nil atom!
x)) ; if x is a atom (nil or the last cdr of an improper list), return x

CL-USER> (filter 'evenp '(24 5 (7) 5 (((4))) 3 ()))
(24 NIL (((4))) NIL)

关于LISP 过滤函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48117356/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com