Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

When using 'define var2 var1', both variables get linked #11

Open
Drogebot opened this issue Dec 30, 2016 · 3 comments
Open

When using 'define var2 var1', both variables get linked #11

Drogebot opened this issue Dec 30, 2016 · 3 comments

Comments

@Drogebot
Copy link

When using this code:

(define var1 '((1 #f #f) (2 #f #f) (3 #f #f)))
(define var2 var1)
(set-nth! (nth var2 2) 2 #t)

The value of the variables after this code is:
var1 = ((1 #f #f) (2 #t #f) (3 #f #f)))
var2 = ((1 #f #f) (2 #t #f) (3 #f #f))) //notice how they both have a #t
But what I would expect the two variables to be is:
var1 = ((1 #f #f) (2 #f #f) (3 #f #f)))
var2 = ((1 #f #f) (2 #t #f) (3 #f #f))) //notice how only var2 has a #t

So basically the two variables get linked, preventing me from making more complex code.
Is this intended and is there a workaround or does this need fixing?

@ToadKing
Copy link
Member

Lists are mutable objects so if you want to modify one while leaving the other alone you should make a copy of it first.

(define var2 (copy var1))

However, it might make sense for define to do this copy implicitly. I'll discuss it with the rest of the team.

@Drogebot
Copy link
Author

ahh, yes that works perfectly! Thanks.

@dastels
Copy link
Contributor

dastels commented Dec 30, 2016

It currently has the correct behaviour. Var2 gets bound to the value of var1. That is a list. So var1 and var2 are bith bound to the same cons cell ie the same list. So if you modify the list it's the same list for both.

But you should try to avoid mutating lists. Or anything, really.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants