我收到以下代码的错误消息。这只是一个简单的语法错误,但作为一个初学者,我不确定是什么错。有人知道吗?
(define qsort
(lambda (input-list)
(define sort-pivot-iter
(lambda (input-list pivot acc)
(let ([current (first input-list)]
[pivot-less (first acc)]
[pivot-greater-equal (first (rest acc))])
(cond (
[(empty? input-list) acc]
[(< current pivot) (sort-pivot-iter (rest input-list) pivot
'((cons current pivot-less) pivot-greater-equal))]
[(>= current pivot) (sort-pivot-iter (rest input-list) pivot
'(pivot-less (cons current pivot-greater-equal)))])))))
(let* ([pivot (first input-list)]
[pivot-sorted (sort-pivot-iter
(rest input-list) pivot (list empty empty))]
[left (first pivot-sorted)]
[right (first (rest pivot-sorted))])
(cond
[(< (length input-list) 2) input-list]
[else (append (qsort left) '(pivot) (qsort right))]))))
(qsort '(2 3 1))
答案 0 :(得分:2)
围绕cond
表单的子句有一组额外的括号,这会导致整个主体被解析为单个子句。
这意味着[(empty? input-list) acc]
被视为表达式(子句的条件),相当于((empty? input-list) acc)
,因为方括号和括号是可互换的。这会尝试调用empty?
的结果作为过程,从而导致错误。
cond
的略微简化的语法如下:
(cond cond-clause ...) cond-clause = [test-expr body ...] | [else body ...+]
请注意,每个cond-clause
都包含在括号(或parens)中,但子句本身不会以任何方式包装。因此,您的cond
表单应如下所示:
(cond
[(empty? input-list) acc]
[(< current pivot) (sort-pivot-iter (rest input-list) pivot
'((cons current pivot-less) pivot-greater-equal))]
[(>= current pivot) (sort-pivot-iter (rest input-list) pivot
'(pivot-less (cons current pivot-greater-equal)))])
您的代码仍有其他一些问题,但这些问题与您问题中的错误消息无关。首先,您在这里使用quote
(又名'
)对我没有意义,所以您可能还想阅读What is the difference between quote and list?来帮助解决这个问题。