Listoflectures IntroductionandFunctionalProgramming ImperativeProgrammingandDataStructures 3 Environment 4 Evaluation 5 ObjectOrientedProgramming 6 Macrosand 7 VirtualMachinesandBytecode 8 GarbageCollectionandNativeCode 9 DistributedComputing 10 Logic 11 Guestlecture 12 Summary 1 TDDA69DataandProgramStructure ImperativeProgramming andDataStructures CyrilleBerger 2 2/51 Lecturegoal Lecturecontent Introducewhatisimperative programming,advantagesand inconvenient Introducedatastructuresandhow theycanbeusedinthedifferent programmingparadigms ImperativeProgramming Statements ConditionalStatement IterativeStatements Advantages/Incovenients Data ArrayandList Tree TreeWalking TreeRecursion Dictionnary 3/51 4/51 Whatisimperativeprogramming? Expresshowcomputationare executed Describescomputationintermofstatements thatchangetheinternalstate Verysimilartorecipes ImperativeProgramming Examples:C/C++,Pascal, Java,Python,JavaScript... 6 Foundationsofimperativeprogramming MosthardwarefollowtheVonNeumannarchitecture,whichisimperative CentralProcessingUnit Inputdevice ControlUnit Arithmetic/LogicUnit Statements Outputdevice MemoryUnit Manyoftheearlyimperativeprogramminglanguages(Fortran,C...)are abstractionsofassemblylanguage ExampleofnonVonNeumann:FPGA(reconfigurablecomputer architecture) 7 Statements Expressionstatements Astatementisexecutedbythe interpretertoperformanaction Sameexpressionsasinfunctional programming 2 plus 'hello' Statement <header>: <statement> <statement> ... <statement> <optionalseparatingheader>: <statement> <statement> ... <statement> ... Suite Clause max ( 2 , Compoundexpressions 3 ) max(min(pow(3,5),-4),min(1,-2)*2)+6 9 10 Assignmentexpression Assignmentexpression a=2;a:=2;a<-2;(seta2)... Global ConditionalStatement 11 if/else ConditionalStatement Astatementthatperformdifferent computationsdependingona booleanexpression InPython: defabs_val(x): if(x<0): return-x elif(x==0): return0 else returnx InECMAScript/JavaScript: functionabs_val(x) { if(x<0) { return-x; }elseif(x===0) { return0; }else{ returnx; } } Howmanystatementsintheabs_valfunction, inPython?InECMAScript? www.govote.at662931 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 ImperativeconditionvsFunctionalcondition Imperative: functionabs_val(x) { varresult; if(x<0) { result=-x; }elseif(x=== 0) { result=0; }else{ result=x; } returnresult; } www.govote.at285968 15 Functional: functionabs_val(x) { returncond(x<0, -x, cond(x=== 0, 0, x); } 16 Booleanexpressions switch InPython: Conditionalswitchbasedonthevalueofan switch(a) { case0: dosomething; break; case'hello' dosomethingelse; break; caseTrue: dosomeother thing; break; } Thisisnotjustsyntaxic Falsevalues:False,0,'',None,0.0,[],{},() Truevalues:anythingelse(True,1,2,'hello'... itgivesperformanceadvantage 17 18 Whileloop IterativeStatements Allowstatementstobeexecuted repeatedlyaslongasa conditionhold i,total=0 whilei<3: i=i+1 total=total+i 20 Forloop Breakstatements Exitthecurrentloop Convenientstatementforloopingon ranges i,total=0 whileTrue: i=i+1 total=total+i ifi<3: break; InJavaScript/ECMAScript: vartotal=0; for(vari=0;i<3;++i) { total=total+i; } InPython: total=0 foriinrange(0,3): total=total+i 21 22 ImperativeProgramming'sstrength Naturalwayofexpressingprograms: Advantages/Incovenients Closetothe Programsarewrittenasalistof Moreefficientthanfunctional Popular Statesareuseful Simulations Howdoyouimplementafunctional randomnumbers? 24 Inconvenients StatesinducesideUnexpectedbehavior Datarace Datastructures 25 Array ArrayandList Collectionofelements,identified byanindex Indexusuallystartsat0 untillength-1 Arraysallowrandom vararray=[1,4,8] console.log(array[0].array[1],array[2]); 28 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 array Eachelementisatwoelementsarray varlist=[1,[4,[8,null]]] Prependanelement: functionprepend(arr,val){ if(is_empty(arr))return[val,null]; return[val,arr]; } Thefirstelementisthe ThesecondisthenextelementoranullExample:varlist=[1,[4,[8,null]] Appendanelement: functionappend(arr,val){ if(is_empty(arr))return[val,null]; varptr=arr; while(ptr[1]!=null) { ptr=ptr[1] } ptr[1]=[val,null] returnarr; } Constructor: functionnew_list(){return[] Emptytest: functionis_empty(arr){returnarr.length ===0;} 31 Suggestasolutionto improvetheappendfunction www.govote.at9943 32 ExampleofListImplementation(3/3) Arrayvslist Eachelementisatwoelementsarray Arrays:random-access,efficient unlessyouneedtoresize Lists:accessthroughiteration, o(1)forinsertion PurelyFunctionalRandom-Access Lists,ChrisOkasaki,InFunctional ProgrammingLanguagesand ComputerArchitecture varlist=[1,[4,[8,null]]] Returnthefirst functionhead(arr){ returnarr[0]; } Returnalltheelementsexceptthe functiontail(arr){ returnarr[1]; } 33 34 Tuple Iterating orderedlistofelements InPython: Usingthearrayindex: Usingthearrayindex: Usingforeach: Usingforeach: functionprint_arr(arr) { for(vari=0;i<arr.length;+ +i) { console.log(arr[i]) } } Notmutablelist Convenientforfunctionreturn: defmake_tuple(a,b,c): return(a,b,c) (a,b,c)=make_tuple(1,2,3) functionprint_arr(arr) { for(varvalofarr) { console.log(val) } } 35 defprint_arr(arr): i=0 while(i<size(arr)): print(arr[i]) defprint_arr(arr): for(valinarr): print(val) 36 Range Arangeisasequenceof range(startingvalue, endingvalue) Tree range(-2,2)->[-2,-1,0,1] Usefulinforloop foridxinrange(0,arr.length): print(arr[idx]) 37 Tree ExampleofTreeImplementation Atreeiseitherasinglevalue calledaleaforasequence oftrees 1 2 4 ø 8 Usinganarray Thefirstelementisthevalue Thesecondisalistofchildren Example: [1,[[2,[]],[4,[[8,[]]]]]] defcreate_tree(val,*children): return[val,list(children)] create_tree(1,createTree(2),createTree(4, createTree(8))) ø 39 40 Listener Atreelistenerisatypeoftreewalkingwhere afunctioniscalledwhenenteringanode andwhenexitingit TreeWalking deftree_listener(tree,entering,exiting): entering(tree) forcintree[1]: tree_listener(c,entering,exiting) exiting(tree) defprint_node(tree): print(tree[0]) tree_listener([1,[[2,[]],[4,[[8,[]]]]]],print_node, >>12248841 42 Visitor Atreevisitorisatypeoftreewalkingthenodes intreearevisitedrecursively deftree_visitor(tree): if(len(tree[1])==0): return1 val=1 forcintree[1]: val=max(val, tree_visitor(c)) returnval+1 tree_visitor([1,[[2,[]],[4,[[8,[]]]]]])>>? www.govote.at192598 TreeRecursion HowwellwouldthatworkinPythonforinfinitely deeptrees? Why?www.govote.at629459 43 TreeRecursion ATree-RecursiveProcess Thecomputationalprocessoffib evolvesintoatreestructure Tree-shapedprocessesarisewhenever executingthebodyofarecursivefunction makesmore n:0,1,2,3,4,5,6,7,8,...,35 fib(n):0,1,1,2,3,5,8,13,21,...,9227465 fib(5) deffib(n): ifn==0: return0 elifn==1: return1 else: returnfib(n-2)+ fib(4) fib(3) fib(3) fib(2) fib(1) fib(2) fib(1) fib(1) fib(2) fib(0) fib(1) fib(1) fib(0) fib(0) 45 46 Memoization RepetitionnTree-RecursiveComputation Thisprocessishighlyrepetitive;fibis calledonthesameargumentmultiple fib(5) times. fib(4) fib(3) fib(3) fib(2) fib(1) fib(2) fib(1) Memoization:storeresultsofexpensivefunction calls fib(1) fib(2) fib(0) fib(1) fib(1) fib(0) __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] Timing: fib(0) fib(9000)->>24h fib_cached(9000)->8.77ms(arrayversion fib_fast_doubling(9000)->6.1ms Howwouldyouimprove? www.govote.at689 47 48 Dictionnary Adictionnaryisanassociativearray,where eachelementisassociatedtoanindex Typeofindex,anythingthatcanbeordered(with <)orcomparedandandevenbetterifahashcan becomputed Dictionnary Integer,notnecesseralycontinuous Strings Example: varmap={1:0,'hello':'world'} console.log(map[1],map['hello']) Inmanydynamicobjectoriented programminglanguages,Objectsare Disctionnaries:Python,JavaScript/ ECMAScript... Summary Imperativeprogramming Data 51/51 50