gpt4 book ai didi

recursion - 使用 Lisp 递归检查连续数字

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

我正在尝试编写一个递归函数来检查列表的元素是否连续增加。

(defun test (lst)   
(if (null lst)
1
(if (= (car lst) (1- (test (cdr lst))))
1
0)))

(setq consecutive '(1 2 3 4))
(setq non-consecutive '(2 5 3 6))

结果是:

CL-USER> (test non-consecutive)
0
CL-USER> (test consecutive)
0

(test consecutive) 应返回 1。如何正确编写此函数?

最佳答案

检查序列中的数字是否连续,即随着第 1 步的增加,你需要这个:

(defun list-consecutive-p (list)
(or (null (cdr list))
(and (= 1 (- (second list) (first list)))
(list-consecutive-p (rest list)))))

然后

(list-consecutive-p '(1 2 3 4))
==> T
(list-consecutive-p '(1 4))
==> NIL
(list-consecutive-p '(4 1))
==> NIL

注意。数字不能很好地替代 bool 值。

附言。我想知道这是否与 How to check if all numbers in a list are steadily increasing? 有关...

关于recursion - 使用 Lisp 递归检查连续数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53820920/

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