Immutability

In the previous chapters we’ve made considerable progress on the infrastructure of our language.

Already we can do a number of cool things that other languages can’t, such as putting code inside lists. Now is the time to start adding in the features which will make our language practical. The first one of these is going to be variables.

They’re called variables, but it’s a misleading name, because our variables won’t vary. Our variables are immutable meaning they cannot change. Everything in our language so far has acted as if it is immutable. When we evaluate an expression we have imagined that the previous thing has been deleted and a new thing returned. In implementation often it is easier for us to reuse the data from the previous thing to build the new thing, but conceptually it is a good way to think about how our language works.

So actually our variables are simply a way of naming values. They let us assign a name to a value, and then let us get a copy of that value later on when we need it.

To allow for naming values we need to create a structure which stores the name and value of everything named in our program. We call this the environment. When we start a new interactive prompt we want to create a new environment to go along with it, in which each new bit of input is evaluated. Then we can store and recall variables as we program.

What happens when we re-assign a name to something new? Isn’t this like mutability?

In our Lisp, when we re-assign a name we’re going to delete the old association and create a new one. This gives the illusion that the thing assigned to that name has changed, and is mutable, but in fact we have deleted the old thing and assigned it a new thing. This is different to C where we really can change the data pointed to by a pointer, or stored in a struct, without deleting it and creating a new one.