Mutation

1 / 9

# Mutation - PowerPoint PPT Presentation

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

I am the owner, or an agent authorized to act on behalf of the owner, of the copyrighted work described.

## PowerPoint Slideshow about 'Mutation' - abia

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.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.

- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript
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:

x

1

2

3

x

1

2

3

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)

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

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?