2014-09-19 34 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)) 
相關問題