使用Lisp递归检查连续数字

时间:2018-12-17 18:15:01

标签: recursion 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 个答案:

答案 0 :(得分:2)

要检查序列中的数字是否连续 ,即 随着步骤1的增加,您需要这样做:

CHOKIDAR_USEPOLLING

然后

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

NB 。数字不能很好地代替布尔值。

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

有关
相关问题