正如标题所述,我需要帮助使函数返回列表中的第二大数字。我真的很坚持,这是我需要在本星期五完成的一项任务。这是我最好的选择,但至少有部分问题是我不完全了解程序的最大值。我从另一个线程复制了它,以尝试将其分解,但是我在所有递归中迷路了。
; I use this to split my list in to two list nested inside a list
(define split-lst
(lambda (lst)
(if (null? lst) '()
(list (take lst 2) (drop lst 2))
)
)
)
; This I have not done myself. Dont fully understand how it works.
(define (maximum L)
(if (null? (cdr L))
(car L)
(if (< (car L) (maximum (cdr L)))
(maximum (cdr L))
(car L)
)
)
)
; Having split my original list using the procedure split-lst above I try to
;compare the values returned by maximum and return the smallest.
(define next-to?
(lambda (a-list)
(split-lst a-list)
(if (< (maximum (car a-list)) (maximum (cdr a-list)))
(car a-list)
(cdr a-list))
)
)
第一行显示的最大错误消息是
(if (null(cdr L))
cdr: contract violation
expected: pair?
given: 1
如果您能帮助它正常工作,我将不胜感激。只是为了澄清它,不需要在最大左右范围内进行明确的工作。谢谢!
答案 0 :(得分:0)
高效的解决方案
按降序排列列表并返回第二个元素:
(define (2nd-max-num l)
(second (sort l >)))