Check consecutive numbers recursively using Lisp

痞子三分冷 提交于 2019-12-25 04:06:30

问题


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



来源:https://stackoverflow.com/questions/53820920/check-consecutive-numbers-recursively-using-lisp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!