使用Lisp递归地检查连续数字



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

(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

注意。数字很难代替布尔值。

PS。我想知道这是否与如何检查列表中的所有数字是否都在稳步增加有关?。。。

最新更新