为什么我的程序没有运行,我收到语法错误? (DrRacket /计划)

时间:2014-09-19 18:50:10

标签: list scheme element racket

我试图编写一个函数,在数字列表的末尾添加一个新数字,但我似乎无法追踪并纠正我的语法错误。有人能帮助我吗?谢谢!

(define (add the-list element)
 (cond 
  ((empty? the-list) (list element)         
   (else (cons (first the-list) cons (add (rest the-list) element))))))

(check-expect (four (list 2 5 4) 1) (list 2 5 4 1)) ; four adds num at the end of lon

1 个答案:

答案 0 :(得分:2)

有两个错位的括号,最后的第二个cons错误,cons期望两个参数。试试这个:

(define (add the-list element) 
  (cond ((empty? the-list) (list element))
        (else (cons (first the-list) 
                    (add (rest the-list) element)))))

使用Racket优秀的编辑器正确格式化和缩进代码,可以轻松检测到这类问题。提示:使用 Ctrl + i 来重新编写代码,它对于发现语法错误非常有用。作为旁注,可以使用现有过程更加惯用地实现相同的过程,如下所示:

(define (add the-list element) 
  (append the-list (list element)))

或者像这样,使用更高阶的程序:

(define (add the-list element)
  (foldr cons (list element) the-list))