在方案中追加新项目到列表的末尾

问题描述:

我需要将一个新项目追加到列表的末尾。这里是我的尝试:在方案中追加新项目到列表的末尾

(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)))))

你的问题主要是语法上的问题。 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)

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)