尝试制作一个检查列表排序的函数
Trying to make a function that checks sorting of a list
我正在尝试创建一个函数,如果列表是有序的,则 returns 为真或为假。我不知道如何使它递归。我不断在最后一行收到错误消息:define: expected only one expression for the function body, but found 1 extra part
(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.
请注意,您没有考虑程序应该 return false
的情况,并且当您发现一个元素相对于下一个元素排序时(您需要不断迭代!这只是一场比赛,其他比赛呢?)。解决办法很简单,只要否定这种情况的条件并询问它是否不是排序returnfalse
。像这样:
(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")) ; true
我正在尝试创建一个函数,如果列表是有序的,则 returns 为真或为假。我不知道如何使它递归。我不断在最后一行收到错误消息:define: expected only one expression for the function body, but found 1 extra part
(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.
请注意,您没有考虑程序应该 return false
的情况,并且当您发现一个元素相对于下一个元素排序时(您需要不断迭代!这只是一场比赛,其他比赛呢?)。解决办法很简单,只要否定这种情况的条件并询问它是否不是排序returnfalse
。像这样:
(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")) ; true