【发布时间】:2016-03-24 20:10:36
【问题描述】:
我正在尝试在方案中将多个列表合并在一起。我必须确保最终列表已排序,但幸运的是这不会太难,因为必须对给定列表进行排序。另一方面,我还必须检查列表是否已排序。
这是我到目前为止的代码:
/* mergeALot 没有完成;出于某种原因,我在“and”和“else”上出现语法错误。另外,我不知道如何检查第一个元素是否是列表(停止迭代)*/
(define (mergeALot a)
(cond (and
ordered? (car a)
ordered? (cadr a))
(mergeALot(cons
(merge (car a)(cadr a))
(cdr (cdr a))))
(else
(display "Some lists are not ordered"))))
(define (ordered? lst)
(cond ((null? lst) #t)
((eq? (length lst) 1) #t)
((> (car (cdr lst)) (car lst))
(ordered? (cdr lst)))
(else #f))
)
(define (merge a b)
(cond ((null? a) b)
((null? b) a)
((>= (car a) (car b))
(cons (car b) (merge a (cdr b))))
(else
(cons (car a) (merge (cdr a) b)))))
【问题讨论】:
-
cond术语周围缺少括号。由于您只有一个结果,您不妨使用if。知道ordered?不使用像(ordered? (car a))这样的括号会计算出一个过程,它是一个真值,因为它不是#f,但您实际上并没有使用该过程。 -
谢谢。不过,我现在遇到了另一个错误;每次我尝试使用 else 语句时,我都会收到错误“else: not allowed as an expression in:”,即使是我能想到的最基本的 if/else 程序,
(define (test a) (if (= 1 2) (#t) (else (#f)))) -
如果不是功课,
(list-sort < (apply append lists))Like:eval.ironscheme.net/?id=173 -
@i'mpotent
if中没有else。这只是(if predicate consequent alternative)例如(if (<= x 3) "You have three or less" "you have more than three")