Upload
owen-parks
View
215
Download
0
Embed Size (px)
DESCRIPTION
New Special Form — set! (set! identifier expression)
Citation preview
Message Passing: Alternative to Generics
• data is “active” — knows how to compute• dispatch on operation
(define (rat (n <integer>) (d <integer>)) (method ((op <symbol>)) (cond ((= op ’numer) n) ((= op ’denom) d) (else: (error ”Bogus operation"))))))
((rat 3 4) ’numer) => 3
In Java:
String m = new String("CS212");
...
if (m.equals("CS211")) { ...
if (m == "CS211") { ...
New Special Form — set!
(set! identifier expression)
set! trashes the substitution model:
(define put-in-bowl (lambda (thing) (set! thing (cons thing '(in a bowl))) thing))
(put-in-bowl 'goldfish)=> (goldfish in a bowl)
Which variable does set! set?
(define x 'barney)=> x
(let ((x 'purple) (y (set! x 'monster))) x)=> ???
x=> ???
Which variable does set! set?
(define x 'barney)=> x
(let* ((x 'purple) (y (set! x 'monster))) x)=> monster
x=> barney
An example not involving set!
(define x 10)
(define foo (lambda () x))
(let ((x 15)) (foo)) => ???
An example not involving set!
(define x 10)
(define foo (lambda () x))
(let ((x 15)) (foo)) => 10
Static vs. Dynamic Scoping
Static scoping:• free variables resolved in the environment of the
function definition
Dynamic scoping:• free variables resolved in the environment of the
function call
Closure:• when a function object is created, the environment
is packaged with it
Referential Transparency
• replace equal values with equal values
• set! destroys referential transparency
The Environment Model
• an extension of the substitution model• more "operational"• fully explains static scoping and the process by
which variable names are resolved in Scheme (and in almost any other programming language.)
An expression only has a value with respectto an environment
Bindingidentifier : value
Frameunordered set of bindings
Environmentordered list of frames
x:10 +:{add}y:20z:30
x:() w:foobar
x:ohy:(list of stuff)
globalenvironment(top level frame)
(machine code foradding numbers)
The Lookup Rule
• the value of an identifier x is the value associated with x in the first (lowest) frame containing abinding for x
• undefined if there aren't any
Define rule
To evaluate (define ident expr):
• evaluate expr in the current environment• add a binding to the top-level frame
(the global environment) Set! rule
To evaluate (set! ident expr):
• evaluate expr in the current environment• look up ident using lookup rule• change that binding to value of expr
x:10 +:{add}y:20z:30
x:() w:foobar
x:ohy:(list of stuff)
x:10 +:{add}y:20 d:12z:30
x:() w:foobar
x:ohy:(list of stuff)
(define d (+ 5 7))
before after
x:10 +:{add}y:20z:30
x:() w:foobar
x:ohy:(list of stuff)
x:10 +:{add}y:20z:30
x:() w:foobar
x:myy:(list of stuff)
(set! x 'my)
before after