Listoflectures TDDA69DataandProgramStructure ImperativeProgramming andDataStructures CyrilleBerger 1IntroductionandFunctionalProgramming 2ImperativeProgrammingandDataStructures 3Parsing 4Evaluation 5ObjectOrientedProgramming 6Macrosand 7VirtualMachinesandBytecode 8GarbageCollectionandNativeCode 9DistributedComputing 10DeclarativeProgramming 11Logic 12Summary 2/59 Lecturecontent ImperativeProgramming Statements ConditionalStatement IterativeStatements ImperativeProgramming Advantages/ Datastructures Arrayand Arrayvslistvs Tree TreeWalking TreeRecursion Dictionnary 3/59 Whatisimperativeprogramming? Foundationsofimperativeprogramming Expresshowcomputationare executed MosthardwarefollowtheVonNeumannarchitecture,whichisimperative CentralProcessingUnit Describescomputationintermofstatements thatchangetheinternalstate Verysimilartorecipes Inputdevice Examples:C/C++,Pascal, Java,Python,JavaScript... ControlUnit Arithmetic/LogicUnit Outputdevice MemoryUnit Manyoftheearlyimperativeprogramminglanguages(Fortran,C...)are abstractionsofassemblylanguage ExampleofnonVonNeumann:FPGA(reconfigurablecomputer architecture) 5 6 Statements Statements Astatementisexecutedbythe interpretertoperformanaction Statement <header>: <statement> <statement> ... <statement> <optionalseparatingheader>: <statement> <statement> ... <statement> ... Suite Clause 8 Expressionstatements Assignmentexpression Sameexpressionsasinfunctional programming 2 plus 'hello' max ( 2 , Compoundexpressions 3 Assignmentexpression a=2;a:=2;a<-2;(seta2)... Global ) max(min(pow(3,5),-4),min(1,-2)*2)+6 9 10 ConditionalStatement ConditionalStatement Astatementthatperformdifferent computationsdependingona booleanexpression 12 if/else InPython: defabs_val(x): if(x<0): return-x elif(x==0): return0 else returnx ImperativeconditionvsFunctionalcondition Imperative: functionabs_val(x) { varresult; if(x<0) { result=-x; }elseif(x=== 0) { result=0; }else{ result=x; } returnresult; } InECMAScript/JavaScript: functionabs_val(x) { if(x<0) { return-x; }elseif(x===0) { return0; }else{ returnx; } } Howmanystatementsintheabs_valfunction, inPython?InECMAScript? www.govote.at841887 start Functional: functionabs_val(x) { returncond(x<0, -x, cond(x=== 0, 0, x); } 13 Whatdoesthisprogramoutput? x=2 y=4 ifx==y2: print("a") else: print("b") ifx: print("c") else: print("d") ifx-2: print("e") else: print("f") 14 Booleanexpressions InPython: Falsevalues:False,0,'',None,0.0,[],{},() Truevalues:anythingelse(True,1,2,'hello'...) www.govote.at575853 start 15 16 switch Conditionalswitchbasedonthevalueofan switch(a) { case0: dosomething; break; case'hello' dosomethingelse; break; caseTrue: dosomeother thing; break; } Thisisnotjustsyntaxic IterativeStatements itgivesperformanceadvantage 17 Whileloop Forloop Allowstatementstobeexecuted repeatedlyaslongasa conditionhold Convenientstatementforloopingon ranges InJavaScript/ECMAScript: vartotal=0; for(vari=0;i<3;++i) { total=total+i; } InPython: total=0 foriinrange(0,3): total=total+i i,total=0 whilei<3: i=i+1 total=total+i 19 20 Breakstatements Exitthecurrentloop i,total=0 whileTrue: i=i+1 total=total+i ifi<3: break; Advantages/Incovenients 21 Inconvenients ImperativeProgramming'sstrength Naturalwayofexpressingprograms: Closetothe Programsarewrittenasalistof Moreefficientthanfunctional Popular Statesareuseful StatesinducesideUnexpectedbehavior Datarace Simulations Howdoyouimplementafunctional randomnumbers? 23 24 Datastructures ArrayandList Array Whyshouldarrayindexstartsat0? Collectionofelements,identified byanindex Indexusuallystartsat0 untillength-1 Arraysallowrandom Historically,inC,arraysareimplementedas pointers Dijkstrasuggeststhatthenaturalnotationto denoteasubsequenceofnaturalnumbers shouldhavethefollowingproperties: 1Thesubsequenceincludesthesmallestnaturalnumber,0 2Thesubsequenceisempty Forthenumbersatob,wecanrepresentit vararray=[1,4,8] console.log(array[0].array[1],array[2]); 1a<i<b 2a≤i<b 3a<i≤b 4a≤i≤b 27 28 (Linked-)List ListOperations A(linked-)listisasequenceof valueswhereeachentry containsapointertothenext 1 element 4 8 Operationsonlist Constructorforcreatinganemptylistnew_list Testifalistisemptyis_empty Prependanelementtothelistprepend Appendanelementtothelistappend Returnthefirstelementhead Returnalltheelementsexceptthefirsttail ø 29 ExampleofListImplementation(1/3) 30 ExampleofListImplementation(2/3) Eachelementisatwoelements Eachelementisatwoelementsarray varlist=[1,[4,[8,null]]] Thefirstelementisthe ThesecondisthenextelementoranullExample:varlist=[1,[4,[8,null]] Prependanelement: deflist_prepend(arr,val): if(list_is_empty(arr)): arr.append(val) arr.append(None) else: arr[1]=[arr[0],arr[1]] arr[0]=val returnarr Constructor: def list_new(): return[] Emptytest: Appendanelement: deflist_append(arr,val): if(list_is_empty(arr)): arr.append(val) arr.append(None) else: ptr=arr while(ptr[1]!=None): ptr=ptr[1] ptr[1]=[val,None] returnarr def list_is_empty(arr): returnlen(arr)==0 31 Suggestasolutionto improvetheappendfunction www.govote.at9943 32 Double-endedqueue ExampleofListImplementation(3/3) Adouble-endedqueue(deque): arrayforwhichelementscanbe addedatthefrontoratthe back Implemented: Eachelementisatwoelements varlist=[1,[4,[8,null]] Returnthefirstelement: def list_head(arr): returnarr[0] Returnalltheelementsexcept circularbuffer centeredinanarray storedinmultiplearrays thefirst: def list_tail(arr): returnarr[1] 33 34 Performance(1/3) Insertionattheback Arrayvslistvsdeque Insertionatthefront Source:http://baptiste-wicht.com/posts/2012/12/cpp-benchmark-vector-list- 36 Performance(2/3) Performance(3/3) Randominsertion Linearsearch Random Sort Source:http://baptiste-wicht.com/posts/2012/12/cpp-benchmark-vector-list- Source:http://baptiste-wicht.com/posts/2012/12/cpp-benchmark-vector-list- 37 Arrayvslist 38 Tuple Arrays:random-access,efficient unlessyouneedtoresize Lists:accessthroughiteration, o(1)forinsertion orderedlistofelements InPython: Notmutablelist Convenientforfunctionreturn: defmake_tuple(a,b,c): return(a,b,c) (a,b,c)=make_tuple(1,2,3) 39 40 Iterating Usingthearrayindex: Usingthearrayindex: Usingforeach: Usingforeach: functionprint_arr(arr) { for(vari=0;i<arr.length;+ +i) { console.log(arr[i]) } } functionprint_arr(arr) { for(varvalofarr) { console.log(val) } } Range Arangeisasequenceof range(startingvalue, endingvalue) defprint_arr(arr): i=0 while(i<size(arr)): print(arr[i]) range(-2,2)->[-2,-1,0,1] Usefulinforloop defprint_arr(arr): for(valinarr): print(val) foridxinrange(0,arr.length): print(arr[idx]) Orinfunctionalprogramming: (take25(squares-of(integers))) 41 42 Tree Tree Atreeiseitherasinglevalue calledaleaforasequence oftrees 1 2 4 ø 8 ø 44 ExampleofTreeImplementation Usinganarray Thefirstelementisthevalue Thesecondisalistofchildren Example: [1,[[2,[]],[4,[[8,[]]]]]] defcreate_tree(val,*children): return[val,list(children)] tree=create_tree(1,create_tree(2), create_tree(4,create_tree(8))) TreeWalking 45 Visitor Listener Atreelistenerisatypeoftreewalking whereafunctioniscalledwhen enteringanodeandwhenexitingit Atreevisitorisatypeoftreewalkingthenodesintreeare visitedrecursively deftree_visitor(tree): if(len(tree[1])==0): return1 val=1 forcintree[1]: val=max(val,tree_visitor(c)) returnval+1 deftree_listener(tree,entering,exiting): entering(tree) forcintree[1]: tree_listener(c,entering,exiting) exiting(tree) tree_visitor([1,[[2,[]],[4,[[8,[]]]]]])>> www.govote.at289943 start HowwellwouldthatworkinPythonforinfinitelydeep trees? defprint_node(tree): print(tree[0]) tree_listener(tree,print_node,print_node) Why?www.govote.at3036 start 47 48 TreeRecursion Tree-shapedprocessesarisewhenever executingthebodyofarecursivefunction makesmore TreeRecursion n:0,1,2,3,4,5,6,7,8,...,35 fib(n):0,1,1,2,3,5,8,13,21,...,9227465 deffib(n): ifn==0: return0 elifn==1: return1 else: returnfib(n-2)+ 50 ATree-RecursiveProcess RepetitionnTree-RecursiveComputation Thecomputationalprocessoffib evolvesintoatreestructure Thisprocessishighlyrepetitive;fibiscalledonthesame argumentmultipletimes. fib(5) fib(5) fib(4) fib(4) fib(3) fib(3) fib(2) fib(1) fib(2) fib(1) fib(1) fib(2) fib(0) fib(1) fib(3) fib(3) fib(1) fib(0) fib(2) fib(1) fib(0) fib(2) fib(1) fib(1) fib(2) fib(0) fib(1) fib(1) fib(0) fib(0) Howwouldyouimprove? www.govote.at5346 start 51 52 Memoization Memoization:storeresultsofexpensivefunction calls __fib_cache={0:0,1:1} deffib_cached(n): ifnin__fib_cache: return__fib_cache[n] else: __fib_cache[n]=fib_cached(n-2) + fib_cached(n-1) return__fib_cache[n] Dictionnary Timing: fib(9000)->>aweek fib_cached(9000)->8.77ms(arrayversion fib_fast_doubling(9000)->6.1ms 53 Dictionnary DictionnaryOperations Adictionnaryisanassociativearray,where eachelementisassociatedtoanindex Typeofindex,anythingthatcanbeordered(with <)orcomparedandandevenbetterifahashcan becomputed Creationofadictionnary: defdict_create(): return[] Setavalue: defdict_set(h,nk,nv): foriinrange(0,len(h)): (k,v)=h[i] if(k==nk): h[i]=(nk,nv) return h.append((nk,nv)) Integer,notnecesseralycontinuous Strings Example: Getavalue: varmap={1:0,'hello':'world'} console.log(map[1],map['hello']) Inmanydynamicobjectoriented programminglanguages,Objectsare Dictionnaries:Python,JavaScript/ ECMAScript... defdict_get(h,nk): foriinrange(0,len(h)): (k,v)=h[i] if(k==nk): returnv returnNone end{pythoncode} 55 56 Hashmap HashmapOperations Inahashmapahashofthekeyiscomputed, usingthathashthevaluesarestoredindifferent bucket Ahashfunctionisafunctionthatmaparbitrary datatofixsize Examples: Createahashmap: defhashmap_create(hash_function, buckets): hash=[hash_function,buckets,[]] foriinrange(0,buckets): hash[2].append(dict_create()) returnhash Setavalue: defhashmap_set(hashmap,key,value): key_hash=hashmap[0](key,hashmap[1]) dict_set(hashmap[2][key_hash],key,value) defhash_integer(k,m): returnk%m defhash_string(k,m): h=0 forcink: h=h+ord(c) returnh%m Getavalue: 57 Summary Imperativeprogramming Data 59/59 defhashmap_get(hashmap,key): key_hash=hashmap[0](key,hashmap[1]) returndict_get(hashmap[2][key_hash], key) 58