gpt4 book ai didi

functional-programming - 检查整数列表是否升序

转载 作者:太空宇宙 更新时间:2023-11-03 18:51:37 25 4
gpt4 key购买 nike

我正在尝试编写一个函数来检查整数列表是否严格升序。我有以下内容:

(: ascending : (Listof Integer) -> Boolean)
;; test whether a list of integers is *strictly* ascending
(define (ascending x)
(match x
('() #f)
((cons hd tl)
(cond
((< hd (second x)) #t)
((> hd (second x)) #f)
(else (ascending tl))))))

它适用于前三个检查,但不适用于下面给出的后三个检查:

(check-expect (ascending (list 1 2 3 4 5)) #t)
(check-expect (ascending (list 5 4 3 2 1)) #f)
(check-expect (ascending (list 5 1 2 3 4)) #f)
(check-expect (ascending (list 1 2 3 5 4)) #f)
(check-expect (ascending (list 1 3 2 4 5)) #f)
(check-expect (ascending (list 1 2 3 4 1)) #f)

我不明白我做错了什么,因为我必须执行以下操作:

  1. 检查列表是否为空并引发错误。完毕。打勾。
  2. 如果列表中只有两个元素,比较hdtl,如果hd <tl 然后 #t,如果没有则 #f。完成勾选。
  3. 其他人对所有整个列表进行两次比较,直到您有一个值 #t#f

请帮忙。

最佳答案

你有几个问题。

首先,您缺少一个只有 1 个元素的列表的情况,这应该是基本情况,然后返回 #t .否则,您将使用 (second x)在只有 1 个元素的列表上,这是一个错误。

接下来,当列表有 2 个或更多元素时,如果第一个元素小于第二个元素,则它是升序的并且列表的尾部也是升序的。您只检查前两个元素。你的else子句仅在第一个和第二个元素相等时运行,因为前两个 cond检查句柄 <> .递归调用不是单独的情况,它与前两个元素升序的情况相结合。

(define (ascending x)
(match x
('() #f) ;; Empty list is error
((cons hd '()) #t) ;; 1-element is success
((cons hd tl)
(if (< hd (second x))
(ascending tl)
#f))))

if也可以简化为:

(and (< hd (second x)) (ascending tl))

关于functional-programming - 检查整数列表是否升序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40517434/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com