Check consecutive numbers recursively using Lisp

2019-08-29 05:04发布

问题:

I'm trying to write a recursive function to check if the elements of a list are increasing consecutively.

(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))

The results are:

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

(test consecutive) should return 1. How can I write this function correctly?

回答1:

To check that the numbers in the sequence are consecutive, i.e., increasing with step 1, you need this:

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

Then

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

NB. Numbers are a poor substitute for booleans.

PS. I wonder if this is related to How to check if all numbers in a list are steadily increasing?...