2014-09-19 53 views
-2

我正在尝试编写一个函数,它会将一个新的数字添加到数字列表的末尾,但我似乎无法追查并纠正我的语法错误。有人能帮助我吗?谢谢!我的程序怎么没有运行,我得到语法错误? (DrRacket/Scheme)

(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 
+0

调用'检查,期望'使用'add',而不是'four'。 – 2014-09-19 19:14:33

回答

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)) 
相关问题