1 / 9

Mutation

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?.

abia
Télécharger la présentation

Mutation

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. 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.

  2. 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.

  3. 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.

  4. 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.

  5. Example • (define x (list 1 2 3)) • We want to change x to the following: x 1 2 3 x 1 2 3

  6. Example x 2 3 1 x 2 3 1 We want to change the cdr of the cddr of x to point to x: (set-cdr! (cddr x) x)

  7. 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 1 2 a b 0 2

  8. 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.

  9. 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?

More Related