【问题标题】:Append new item to end of list in scheme将新项目附加到方案列表的末尾
【发布时间】:2017-12-19 02:01:07
【问题描述】:

我需要在列表末尾追加一个新项目。这是我尝试过的:

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

我希望看到:

(1 2 3 4 5)

但我收到:

let: (let ((new-list (append my-list (list 5))))) 中的语法错误(缺少绑定 pair5s 或主体)

【问题讨论】:

    标签: list scheme let


    【解决方案1】:

    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 表单之外不存在。

    这是 Algol 的等价物(特别是在 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)
    

    【讨论】:

      【解决方案2】:

      您的问题主要是句法性质的。 Scheme 中的let 表达式具有(let (binding pairs) body) 的形式。在您的示例代码中,虽然您确实有一个应该工作的绑定,但您没有正文。要使其正常工作,您需要将其更改为

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

      在我的 DrRacket 6.3 中,它的评估结果符合您的预期:'(1 2 3 4 5)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2022-06-22
        • 2018-07-27
        • 2012-09-25
        • 2016-06-17
        • 2011-07-11
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多