【问题标题】:Sorting a list of list in Scheme对 Scheme 中的列表进行排序
【发布时间】:2018-02-06 05:13:44
【问题描述】:

我有一个函数,它接受一个列表并输出该列表的幂集。因此,(1 2 3) 应该输出 (() (1) (2) (3) (1 2) (1 3) (2 3) (1 2 3))

我目前得到的值是正确的,只是顺序不太好。当前输出为(() (3) (2) (2 3) (1) (1 3) (1 2) (1 2 3))

我编写了两个函数,它们将传递给标准排序函数来检查每个元素的长度,以及它是否有序并进行相应的排序。它的输出给了我((1 2 3) (1 2) (1 3) (1) (2 3) (2) (3) ())

鉴于最终列表是(() (3) (2) (2 3) (1) (1 3) (1 2) (1 2 3)),我在这两个函数中做错了什么?

;定义元素有序

(define (element-ordered? ls0 ls1)
    (cond
        [(equal? ls0 ls1) #t]
        [(< (car ls0) (car ls1)) #t]
        [else #f]))

;定义长度排序

(define (length-ordered? ls0 ls1)
    (cond
        [< (length ls0) (length ls1) #t]
        [> (length ls0) (length ls1) #f]
        [eq? (length ls0) (length ls1) (element-ordered? ls0 ls1)]))

;使用提供的排序进行排序

(sort final-list length-ordered?))

【问题讨论】:

    标签: list sorting scheme


    【解决方案1】:

    我不确定您的element-ordered? 函数是否完全正确。这是我想出的:

    (define (element-ordered? ls0 ls1)
        (cond
            ((< (car ls0) (car ls1)) #t)
            ((> (car ls0) (car ls1)) #f)
            (else (element-ordered? (cdr ls0) (cdr ls1)))
        )
    )
    
    (define (length-ordered? ls0 ls1)
        (cond
            ((< (length ls0) (length ls1)) #t)
            ((> (length ls0) (length ls1)) #f)
            (else (element-ordered? ls0 ls1))
        )
    )
    

    另请注意,在您的代码 sn-p 中,length-ordered? 的条件没有正确括起来,因此这也可能导致您的函数出现问题。

    【讨论】:

    • 我按长度顺序修复了括号?通过您的轻微修复,我收到了预期的输出。感谢您的帮助!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-12-22
    • 2014-06-21
    • 2018-11-06
    • 1970-01-01
    • 2015-03-05
    • 2018-07-01
    • 1970-01-01
    相关资源
    最近更新 更多