使用Lisp递归检查连续数字 [英] Check consecutive numbers recursively using Lisp

查看:120
本文介绍了使用Lisp递归检查连续数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个递归函数,以检查列表中的元素是否连续增加.

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

结果是:

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

(test consecutive)应该返回1.如何正确编写此函数?

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

然后

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

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

NB. Numbers are a poor substitute for booleans.

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

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

这篇关于使用Lisp递归检查连续数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆