Mutation So far, our data abstractions consists of the following: –Constructors –Selectors/Accessors –Operations –Contract Once a data object is created, it never changes. Today, we’ll talk about how to alter the internal structure of data objects.
Why Mutation? Saves space- can make small changes to existing object instead of creating new ones. More freedom in creating data types- can freely manipulate pointers to alter structure of cons cells and lists.
Tools of Mutation: basic (set! var x) –Evaluate x. Do not evaluate var. Instead, find its binding and change it to take on the value of x. –Difference between set! and define: define always creates new binding. set! alters existing binding.
Tools of Mutation: Data Structures (set-car! pair x) –Changes car pointer in pair to point to value of x. (set-cdr! pair x) –Changes cdr pointer in pair to point to value of x.
Example (define x (list 1 2 3)) We want to change x to the following: 123 x 123 x
Example x 1 23 x 1 23 We want to change the cdr of the cddr of x to point to x: (set-cdr! (cddr x) x)
Side Effects Mutation can cause unexpected side effects. Example: (define a (list 1 2)) (define b a) (set-car! a 0) a => (0 2) b => (0 2) a b 12 a b 02
Equality 2 tests for equality: –(eq? x y) Tests if x and y point to exactly the same object. If x and y are “eq”, then a change to one should be visible in the other as well –(equal? x y) Tests whether x and y print to the same thing Internal structure of x and y not necessarily the same.
Summary Mutation allows us to change existing bindings and pointers. Saves space and allows more programming freedom. However, must be careful with side effects New notions of equality: –Object equality: eq? –Looks the same: equal?