Reputation: 31
I need to append a new item to the end of a list. Here is what I tried:
(define my-list (list '1 2 3 4))
(let ((new-list (append my-list (list 5)))))
new-list
I expect to see:
(1 2 3 4 5)
But I receive:
let: bad syntax (missing binding pair5s or body) in (let ((new-list (append my-list (list 5)))))
Upvotes: 3
Views: 1296
Reputation: 48745
A let
makes a local variable that exists for the duration of the let
form. Thus
(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
Your error message tells you that you have no expression in the let
body which is a requirement. Since I added one in my code it's allowed. However now you get an error when you try evaluating new-list
since it doesn't exist outside the let
form.
Here is the Algol equivalent (specifically in 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.
Since you already tried using define
you can do that instead and it will create a variable in the global or function scope:
(define my-list '(1 2 3 4))
(define new-list (append my-list (list 5)))
new-list ; ==> (1 2 3 4 5)
Upvotes: 0
Reputation: 9805
Your problem is mostly of syntactical nature. The let
expression in Scheme has the form (let (binding pairs) body)
. In your example code, while you do have a binding that should work, you don't have a body. For it to work, you need to change it to
(let ((new-list (append my-list (list 5))))
new-list)
In my DrRacket 6.3 this evaluates to what you would expect it to: '(1 2 3 4 5)
.
Upvotes: 1