2017-07-14 65 views
2

我需要將一個新項目追加到列表的末尾。這裏是我的嘗試:在方案中追加新項目到列表的末尾

(define my-list (list '1 2 3 4)) 
(let ((new-list (append my-list (list 5))))) 
new-list 

我希望看到:

(1 2 3 4 5) 

但我得到:

令:語法錯誤(缺少約束力pair5s或身體)中(讓( (new-list(append my-list(list 5)))))

回答

1

你的問題主要是語法上的問題。 Scheme中的let表達式的格式爲(let (binding pairs) body)。在你的示例代碼中,當你確實有一個可以工作的綁定時,你沒有一個body。對於它的工作,你需要將其更改爲

(let ((new-list (append my-list (list 5)))) 
    new-list) 

在我DrRacket 6.3這個計算結果爲,你會期待它什麼:'(1 2 3 4 5)

0

A let產生一個局部變量,該變量在let表單的持續時間內存在。因此

(let ((new-list (append my-list '(5)))) 
    (display new-list) ; prints the new list 
) ; ends the let, new-list no longer exist 

new-list ; error since new-list is not bound 

你的錯誤信息告訴你,你在let體是一個要求沒有任何表情。由於我在代碼中添加了一個,因此允許。但是,如果您在嘗試評估new-list時遇到錯誤,因爲它不在let表單之外。

這裏是陵當量(特別是在JS)

const myList = [1,2,3,4]; 
{ // this makes a new scope 
    const newList = myList.concat([5]); 
    // at the end of the scope newList stops existing 
} 
newList; 
// throws RefereceError since newList doesn't exist outside the block it was created. 

由於您使用define你能做到這一點,而不是,它會在全球性或功能範圍內創建一個變量已經嘗試過:

(define my-list '(1 2 3 4)) 
(define new-list (append my-list (list 5))) 
new-list ; ==> (1 2 3 4 5)