0

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?

6
  • your recursion tests (car lst) vs. (1- "return of test call"), that is always (1- 0) or (1- 1) Commented Dec 17, 2018 at 18:21
  • How to arrange that part correctly in a recursive manner? Commented Dec 17, 2018 at 18:28
  • What should (test '(1 3 5 7)) return? Commented Dec 17, 2018 at 18:45
  • @sds consecutive odd numbers need not be checked at all. Aynway, if I can check the '(1 2 3 4) sequence, I can check for it too I guess. By the way is the '(1 2 3 4) sequence called also the "successive numbers" in English? What is the most correct name for such a sequence, i.e. wehre the numbers increase one by one? Commented Dec 17, 2018 at 19:09
  • @Romario: Are you testing consecutive or increasing? Commented Dec 17, 2018 at 19:10

1 Answer 1

2

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?...

Sign up to request clarification or add additional context in comments.

4 Comments

That looks fine. The 'or' & 'and' construct is what I thought of initially but which I couldn't do.
That's because you are trying to return numbers instead of booleans.
Yes. At first I 've done it using booleans (i.e. nil & t) but the Lisp compiler threw errors like "nil is not an integer" and the CLISP compiler in particular exited whenever I tried to run it. So I tried in vain doing it with the numbers :)
That's because you tried to conflate the step with the return value.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.