List of lectures TDDA69 Data and Program Structure

advertisement
Listoflectures
IntroductionandFunctionalProgramming
ImperativeProgrammingandDataStructures
3
Environment
4
Evaluation
5
ObjectOrientedProgramming
6
Macrosand
7
VirtualMachinesandBytecode
8
GarbageCollectionandNativeCode
9
DistributedComputing
10
Logic
11
Guestlecture
12
Summary
1
2
TDDA69DataandProgramStructure
Environment
CyrilleBerger
2/35
Lecturecontent
Environment
EvaluationandEnvironment
AssignmentandEnvironment
FunctionsandEnvironment
Scope
Environment
TheScopeTrap
3/35
Assignment
Bindsnamesto
a
:=
2
a
plus
2
Environment
FromtheSICPBook,section3.2:
Bindingsassociatevariablestovalues(inassignment
expression)
Aframeisasetofbindings
Anenvironmentisasequenceofframes
Environmentsdescribecontextswhereexpressionsare
evaluated
Everyframepointstothefollowingframeintheenvironment
Allenvironmentshaveaglobalframeasthelastframeinthe
sequence
Theglobalenvironmentisaframewithallpredefined
bindings
Scopetherangeinwhichavariablecanbereferenced
Nowahasthevalue2
evaluatesto4
Thisimplythataisstored
somewhere!
5
6
EnvironmentDiagram
nil:...
pi:3.14...
...
f:6
m:{'key':1}
...
(global)I
a:6
f:[34]
...
II
m:1
y:2
...
III
IV
a:1
...
V
a:2
m:4
...
VI
EvaluationandEnvironment
7
Evaluationofanexpression
NameshavenoMeaningwithoutEnvironments
Variables(andhence
expressions)donothave
meaningsinthemselves
Variablesforwhichthereisno
bindinginanenvironmentaresaid
tobeunbound
Avariablecanhaveatmostone
bindingperframe
NameshavenoMeaning
withoutEnvironments...
...soexpressionsneedtobe
associatedtoan
environment
Buthowdowegetthevalue
of'a'?
a
plus
2
9
Namelook-up(1/2)
10
Namelook-up(2/2)
Ifseveralbindingsexistforthe
samevariableinan
thenthevariableisassociatedtotheclosest
environment
Whatisthevalueofa?
Whatisthevalueoff?
Govoteat(forframeII)
www.govote.at7377
56
Govoteat(forframeVI)
www.govote.at228098
binding
thatbindingissaidtoshadowtheother
bindingsofthevariable
f:6
m:{'key':1}
...
11
nil:...
a:3...
...
(global)I
a:6
f:2
...
II
m:1
y:2
...
III
IV
a:1
...
V
a:2
m:4
...
VI
12
EnvironmentsDiagrams
Environment
diagrams
visualizethe
interpreter's
process
AssignmentandEnvironment
nil:...
pi:3.14...
...
(global)I
II
a:6
f:[34]
...
VI
a:2
m:4
...
14
AssignmentStatement(1/2)
Startina
cleanstate
a=
b=2
b,a=a+b,
a=2
b=3
AssignmentStatement(2/2)
f=min
g=max
g,h=min,max
max=g
max(f(2,g(h(1,5),3)),4)
(global)I
15
(global)I
min=funcmin(...)
max=funcmax(...)
16
Inwhichframetobind?
WeareinFrame
a=
b=1
Whereshouldthe
bindingofaandb
bedone?
a:0
c:34
(global)I
II
b:3
FunctionsandEnvironment
17
CallingUser-DefinedFunctions(1/2)
CallingUser-DefinedFunctions(2/2)
Procedureforcallinguser-defined
functions:
fromoperatorimportmul
defsquare(x):
returnmul(x,x)
square(-2)
Addalocalframe
Bindthefunction'sformalparameterstoits
argumentsinthatframe
Executethebodyofthefunctioninthatnew
frame
(global)I
x:-2
19
(square)II
20
Recursion
NamesHaveDifferentMeaningsinDifferentEnvironments
fromoperatorimportmul
defsquare(square):
⠀⠀returnmul(square,square)
square(-2)
(global)I
mul:funcmul(...)
square:funcsquare(...)
(square)II
square:-2
Thesamefunctionis
calledmultipletime
Differentframeskeeptrackof
thedifferentargumentsineach
call.
Whatnevaluatestodepends
uponwhichisthecurrentcontext.
21
22
RecursioninEnvironmentDiagram
deffact(n):
n:3
ifn==0:
return1
else:
returnn*fact(n-1)
fact(3)
⠀↳fact(2)
⠀⠀↳fact(1)
⠀⠀⠀↳fact(0)
n:1
(fact)II
n:2
(fact)III
Scope
(global)I
mul:funcmul(...)
square:funcsquare(...)
(fact)IV
n:0
(fact)V
23
LocalvsGlobal(1/4)
deff():
print(s)
s='World'
f()
LocalvsGlobal(2/4)
(global)I
f:funcf(...)
s:'World'
(f)II
deff():
s='Hello'
print(s)
s='World'
f()
(global)I
f:funcf(...)
s:'World'
s:'Hello'
25
LocalvsGlobal(3/4)
deff():
print(s)
s='Hello'
print(s)
s='World'
f()
UnboundLocalError:local
variable's'referenced
beforeassignment
26
LocalvsGlobal(4/4)
(global)I
f:funcf(...)
s:'World'
s:undefined
(f)II
(f)II
27
deff():
globals
print(s)
s='Hello'
print(s)
s='World'
f()
(global)I
f:funcf(...)
s:'Hello'
(f)II
28
InJavaScript
functionf()
{
vars='Hello'
console.log(s)
}
s='World'
f()
console.log(s)
Functions-scopevsBlock-scope
Python,JavaScript,Lisp...
havefunction-scope
C,C++,Java...haveblockForinstanceinC+
functionf()
{
console.log(s)
s='Hello'
console.log(s)
}
s='World'
f()
inta=1;
{
inta=2
}
std::cout<<a<<std::endl;
29
30
TheScopetrap
TheScopeTrap
functioncreate_arr()
{
vararr=[]
for(vari=0;i<4;++i)
{
arr[i]=function(){console.log(i)}
}
returnarr;
}
for(vari=0;i<4;++i)
{
arr[i]()
}
Whatisprinted?www.govote.at4049
Howtosolve?www.govote.at9648
32
OutoftheScopeTrap
TheScopeTrapinC++
functioncreate_arr()
{
vararr=[]
for(vari=0;i<4;++i)
{
arr[i]=(function(value){returnfunction(){console.log(value)}})(i)
}
returnarr;
}
#include<vector>
#include<functional>
#include<iostream>
std::vector<std::function<void()>>create_arr()
{
std::vector<std::function<void()>>val;
for(inti=0;i<4;++i)
{
val.push_back([i](){std::cout<<i<<std::endl;});
}
returnval;
}
intmain(intargc,char**argv)
{
std::vector<std::function<void()>>arr=
create_arr();
for(std::function<void()>v:arr)
{
v();
}
}
arr=create_arr()
for(vari=0;i<4;++i)
{
arr[i]()
}
([i](){...})I
i:1
(global)I
i:1
(for(...))II
InC++,capturedvariablesarecopiedinthelambdaframe
33
Conclusion
Environment
Assignment
Functioncall
Scope:localvsglobal
35/35
34
Download