我正在尝试创建一个函数,如果列表是正确的,则返回true或false。我不知道如何使它是递归的。我一直收到最后一行的错误消息: define: expected只对函数体有一个表达式,但是找到了一个额外的部分
(check-expect (is-sorted? (list)) true)
(check-expect (is-sorted? (list "A")) true)
(check-expect (is-sorted? (list "B" "A")) false)
(check-expect (is-sorted? (list "A" "B")) true)
(check-expect (is-sorted? (list "A" "C" "B")) false)
(check-expect (is-sorted? (list "A" "B" "C")) true)
(define (is-sorted? lst)
(cond
((empty-list? lst) true)
((= (length lst) 1) true) ;return true if there is only one element.
((string<? (first lst) second lst) true) ;If the first element is smaller than the second
;return true.
(else (is-sorted? (rest lst))))) ;do the above steps on the rest of the elements in the list.发布于 2021-11-02 09:26:52
请注意,您没有考虑过程何时应该返回false的情况,并且当您发现一个元素相对于下一个元素排序时,提前退出(您需要继续迭代!)这只是一场比赛,其他的呢?)解决方案很简单,只需否定这种情况的条件,并询问它是否没有排序返回false。如下所示:
(define empty-list? empty?)
(define (is-sorted? lst)
(cond
((empty-list? lst) true)
((empty-list? (rest lst)) true)
((string>=? (first lst) (second lst)) false)
(else (is-sorted? (rest lst)))))它适用于您的测试用例:
(is-sorted? (list)) ; true
(is-sorted? (list "A")) ; true
(is-sorted? (list "B" "A")) ; false
(is-sorted? (list "A" "B")) ; true
(is-sorted? (list "A" "C" "B")) ; false
(is-sorted? (list "A" "B" "C")) ; truehttps://stackoverflow.com/questions/69803743
复制相似问题