Example: stock market

Lecture 4: Functional Programming Languages (SML)

ProgrammingLanguagesLecture4: FunctionalProgrammingLanguages (SML) Benja minJ. KellerDepartment of ComputerScience,VirginiaTechProgrammingL anguages|Lecture3 |FunctionalLanguages (SML) 2 LectureOutline Overview Primitive DataTypes (Built-in)StructuredDataTypes PatternMatching Type Inference Polymorphism Declarations ExamplesProgrammingLanguages|Lecture3 |FunctionalLanguages (SML) 3 LectureOutline Exceptions HigherOrderFunctions ProgramCorrectness Imperative LanguageFeatures Implementation E ciency Concurrency SummaryProgrammingLanguages|Lecture3 |FunctionalLanguages (SML) 4 Overviewof ML Developed in Edinburghin late1970's Meta-Languageforautomatedtheoremprovings ystem Designedby RobinMilner,Mike Gordon,ChrisWadsworth Foundusefulandextendedto programminglanguageProgrammingLanguages| Lecture3 |FunctionalLanguages (SML) 5 FunctionalProgrammingin ML Functionalprogramsaremadeupof functionsappliedto data We writeexpressionsratherthancommands Purefunctionallanguageshave nosidee ects MLis nota purelanguage{referencevariables{commands {I/OProgrammingLanguages|Lecture3 |FunctionalLanguages (SML) 6 MLCharacteristics Functionsas rstclassvalues Staticallyscoped Statictypingviatype inference Polymorphictypes Type systemincludessupportforADTs Exceptionhandling GarbagecollectionProgrammingLanguages|Le cture3 |FunctionalLanguages (SML) 7 UsingMLInterpreter TypesmlStandardML of NewJersey, ,January30,1998- Hyphen(-) is prompt Canloadde nitionsfrom " "; Endsessionby typingctrl-dProgrammingLanguages|L}}}

Programming Languages Lecture 4: Functional Programming Languages (SML) Benjamin J. Keller Department of Computer Science, Virginia Tech

Tags:

  Lecture, Programming, Language, Functional, Lecture 4, Functional programming languages

Information

Domain:

Source:

Link to this page:

Please notify us if you found a problem with this document:

Other abuse

Advertisement

Transcription of Lecture 4: Functional Programming Languages (SML)

1 ProgrammingLanguagesLecture4: FunctionalProgrammingLanguages (SML) Benja minJ. KellerDepartment of ComputerScience,VirginiaTechProgrammingL anguages|Lecture3 |FunctionalLanguages (SML) 2 LectureOutline Overview Primitive DataTypes (Built-in)StructuredDataTypes PatternMatching Type Inference Polymorphism Declarations ExamplesProgrammingLanguages|Lecture3 |FunctionalLanguages (SML) 3 LectureOutline Exceptions HigherOrderFunctions ProgramCorrectness Imperative LanguageFeatures Implementation E ciency Concurrency SummaryProgrammingLanguages|Lecture3 |FunctionalLanguages (SML) 4 Overviewof ML Developed in Edinburghin late1970's Meta-Languageforautomatedtheoremprovings ystem Designedby RobinMilner,Mike Gordon,ChrisWadsworth Foundusefulandextendedto programminglanguageProgrammingLanguages| Lecture3 |FunctionalLanguages (SML) 5 FunctionalProgrammingin ML Functionalprogramsaremadeupof functionsappliedto data We writeexpressionsratherthancommands Purefunctionallanguageshave nosidee ects MLis nota purelanguage{referencevariables{commands {I/OProgrammingLanguages|Lecture3 |FunctionalLanguages (SML) 6 MLCharacteristics Functionsas rstclassvalues Staticallyscoped Statictypingviatype inference Polymorphictypes Type systemincludessupportforADTs Exceptionhandling GarbagecollectionProgrammingLanguages|Le cture3 |FunctionalLanguages (SML) 7 UsingMLInterpreter TypesmlStandardML of NewJersey, ,January30,1998- Hyphen(-) is prompt Canloadde nitionsfrom " "; Endsessionby typingctrl-dProgrammingLanguages| Lecture 3 |FunctionalLanguages (SML) 8 Expressions Expressionevaluation- 3;valit = 3 : int- 23 - 6;valit = 17 : int Nameitrefersto lastvaluecomputedProgrammingLanguages|Le cture3 |FunctionalLanguages (SML) 9 Constants In MLwe namevaluesratherthanhave variables:- valpi = ;valpi = : real- valr =.}}}

2 Valr = : real- valarea= pi * r * r;valarea= : real A namecanbe rebound- valarea= "pir squared";valarea= "pir squared": stringProgrammingLanguages|Lecture3 |FunctionalLanguages (SML) 10 Functions Syntax:funnamearg= expression Example- funarea(r)= pi*r*r;valarea= fn : real-> real Parenthesisoptionalforsingleargument Canalsowritefunctionas a value- valarea= fn r => pi * r * r;valarea= fn : real-> realProgrammingLanguages|Lecture3 |FunctionalLanguages (SML) 11 Functionapplications- ;valit = : real- area( );valit = : realProgrammingLanguages|Lecture3 |FunctionalLanguages (SML) 12 Environment pide nedoutsideofareavalpi = ;funarea(r)= pi*r*r; Whathappensif changepi?- ;valit = : real- valpi = 2000;valpi = 2000: int- ;valit = : real Environment of functiondeterminesvalueProgrammingLangua ges|Lecture3 |FunctionalLanguages (SML) 13 Primitive DataTypes unit| hasonevalue:() bool{values:true,false{operators:not,and also,orelse int{values:positive andnegative integers(..~2,~1,0,1,2,.. ).{operators:+,-,*,div,mod,<,<=,>,>=,<>ProgrammingLanguages|Lecture3 |FunctionalLanguages (SML) 14 Primitive DataTypes (cont) real{ , {operators:+,-,*,/,<,<=,>,>=,<>,log,exp,sin,arctan string{values:"a string",usesspecialcharacters\t,\n{opera tors:^(concatenation),length,substringPr ogrammingLanguages|Lecture3 |FunctionalLanguages (SML) 15 Type InferenceandOverloading MLattemptsto infertype fromvaluesof expressions Someoperatorsoverloaded(+,*,-) Inferredtype may notbe whatyouwant- fundoublex = x + x;valdouble= fn : int-> int SometimesMLcan'tdeterminetype Forcetype withtype constraintsfundoublex:real= x + x;fundouble(x):real= x + x;fundouble(x:real):real= x + x;hastypefn : real-> realProgrammingLanguages|Lecture3 |FunctionalLanguages (SML) 16 StructuredDataTypes Tuples|orderedcollectionof values Records|collectionof namedvalues Lists| listof valuesof homogeneoustypeProgrammingLanguages|Lect ure3 |FunctionalLanguages (SML) 17 Tuples Syntax:( exp-list)- ( 1, 2, 3).}}}}}}}}

3 Valit = (1,2,3): int* int* int- (pi,r,area);valit = ( , ,fn): real* real* (real-> real) Accessby patternmatchingor by label- val(a,b) = ( ,"zippy");vala = : realvalb = "zippy": string- #3 (a,b, pi);valit = : realProgrammingLanguages|Lecture3 |FunctionalLanguages (SML) 18 Multi-Argument Functions Argument of a functioncanbe a tuple- funmult(x,y)= x*y;valmult= fn : int* int-> int- funmult(t : int*int)= #1 t * #2 t; (* ugly!*)valmult= fn : int* int-> intProgrammingLanguages|Lecture3 |FunctionalLanguages (SML) 19 CurriedFunctions Functionwithtwo arguments- funpower(m,n): int== if n = 0 then1= elsem * power(m,n-1);valpower= fn : int* int-> int Equivalent function- funcpowerm n : int== if n = 0 then1= elsem * cpowerm (n-1);valcpower= fn : int-> int-> intProgrammingLanguages|Lecture3 |FunctionalLanguages (SML) 20 CurriedFunctions(cont) powerandcpowerdi erent functions,but- power(2,3);valit = 8 : int- cpower2 3;valit = 8 : int Functioncpoweris \Curried"(HaskellCurry) Cande nenewfunctionsby partialevaluation- valpower_of_two= cpower2;valpower_of_two= fn : int-> int- power_of_two3;valit = 8 : intProgrammingLanguages|Lecture3 |FunctionalLanguages (SML) 21 Records A collectionof labeleddataitems- valex = { name= "george",userid= 12 };valex = {name="george",userid=12} :{name:string,userid:int} Accesselements by patternmatchingor label- #nameex;valit = "george": string- val{name=username.}

4 }= ex;valusername= "george": string Tuplesshorthandforrecordswithlabels1,2, ..ProgrammingLanguages|Lecture3 |FunctionalLanguages (SML) 22 Lists Allelements mustbe of sametype- [ 2, 6, 4, 9];valit = [2,6,4,9]: intlist- [ "a","b","c"];valit = ["a","b","c"]: stringlist- [ 1, "a"];..Error:operatorandoperanddon'tagre eoperatordomain:int* intlistoperand:int* stringlistin expression:1 :: "a":: nilProgrammingLanguages|Lecture3 |FunctionalLanguages (SML) 23 ListsConstructors [],nil| empty list(alltypes) ::|consoperator- 1 :: [];valit = [1]: intlist- 1 :: (2 ::[2]);valit = [1,2,2]: intlistProgrammingLanguages|Lecture3 |FunctionalLanguages (SML) 24 FunctionsonLists length Headandtail- hd [ 3, 4];valit = 3 : int- tl [3,4];valit = [4]: intlist Concatenation- [ 1, 2] @ [3,4];valit = [1,2,3,4]: intlist rev| reverselistProgrammingLanguages|Lecture3 |FunctionalLanguages (SML) 25 MapFunction mapapplysanotherfunctionto allelements of a list- funsqrx = x* x;valsqr= fn : int-> int- mapsqr[2,3,4,5];valit = [4,9,16,25]: intlist Exampleofpolymorphicandhigherorderfuncti on- map;valit = fn : ('a-> 'b)-> 'a list-> 'b listProgrammingLanguages|Lecture3 |FunctionalLanguages (SML) 26 PatternMatching Patternmatchingimportant in ML Usedto bindvariables- val(x,y)= (5 div2, 5 mod2).

5 Valx = 2 : intvaly = 1 : int- val{a = x, b = y} = {b = 3, a = "one"};valx = "one": stringvaly = 3 : intProgrammingLanguages|Lecture3 |FunctionalLanguages (SML) 27 PatternMatching Patternmatchingonlists- valhead::tail= [1,2,3]; :bindingnotexhaustivehead:: tail= ..valhead= 1 : intvaltail= [2,3]: intlist- valhead::_= [4,5,6];(* "_"wildcard*) :bindingnotexhaustivehead:: _ = ..valhead= 4 : intProgrammingLanguages|Lecture3 |FunctionalLanguages (SML) 28 PatternMatchingin Functions Candopatternmatchingin functionsfunproduct[] : int= 1| product(h::t)= h * productt; May usedi erent types like integers- funoneTo0 = []= | oneTon = n::(oneTo(n-1));valoneTo= fn : int-> intlist- oneTo5;valit = [5,4,3,2,1]: intlist Example(de nitionof reverse)funreverse[] = []| reverse(h::t)= reverse(t)@ [h];ProgrammingLanguages|Lecture3 |FunctionalLanguages (SML) 29 Aside:FunctionComposition Cande nefactorialasfunfactn = product(oneTon); Equivalent to writingvalfact= producto oneTo; Theoperatorois functioncompositionProgrammingLanguages| Lecture3 |FunctionalLanguages (SML) 30 Type Inference MLdeterminestypes of expressionsor functions Don'thave to declaretypes exceptto disambiguatetypes- valx = ;valx = : real- funaddxy = x + y.

6 Valaddx= fn : real-> real LanguagestronglytypedProgrammingLanguage s|Lecture3 |FunctionalLanguages (SML) 31 PolymorphicFunctions Polymorphism|many \forms"(types) A functionfunlast[x]= x| last(h::t)= lastt;hastypefn : 'a list-> 'a Symbol'ais a type variable Type variablesfortypes withequality have form''afunsearchitem[] = false| searchitem(fst::rest)=if item= fstthentrueelsesearchitemrest;hastypefn : ''a-> ''alist-> boolProgrammingLanguages|Lecture3 |FunctionalLanguages (SML) 32 Declarations Functionandvaluedeclarationsat thetoplevel stay visibleuntil a newde nitionof sameidenti er- valx = 3 * 3;valx = 9 : int- 2 * x;valit = 18 : intProgrammingLanguages|Lecture3 |FunctionalLanguages (SML) 33 LocalDeclarations Declarationswithinfunctions Syntax:letdeclinexpendfunfactn =letfunfacti(n,p)=if n = 0 thenpelsefacti(n-1,n*p);infacti(n,1)end; AllowsnamingintermediatevaluesProgrammin gLanguages|Lecture3 |FunctionalLanguages (SML) 34 HidingDeclarations Declarationscanbe hiddenwithlocal Syntax:localdeclindecl-listendlocalfunfa cti(n,p)=if n = 0 thenpelsefacti(n-1,n*p);infunfactn = facti(n,1);end; CandeclareseveralfunctionsProgrammingLan guages|Lecture3 |FunctionalLanguages (SML) 35 Orderof Evaluation Evaluateoperand,substituteoperandvaluefo rformalparameter,andevaluate Insiderecord,evaluate eldsfromleftto right Insideletexpressionletdeclinexpend1.

7 Evaluatedeclproducingnewenvironment2. evaluateexpin newenvironment3. restoreoldenvironment4. returncomputedvalueof expProgrammingLanguages|Lecture3 |FunctionalLanguages (SML) 36 Declarations SequentialDeclarations- valx = 12;valx = 12 : int- valy = x + 2;valy = 14 : int Parallel(Simultaneous)Declarations- valx = 2 andy = x + 3;valx = 2 : intvaly = 15 : intProgrammingLanguages|Lecture3 |FunctionalLanguages (SML) 37 MutualRecursion Example:take alternateelementsfuntake[] = []| take(h::t)= h::(skipt)andskip[] = []| skip(h::t)= taket; Output- take[1,2,3,4,5,6];valit = [1,3,5]: intlist- skip[1,2,3,4,5,6];valit = [2,4,6]: intlistProgrammingLanguages|Lecture3 |FunctionalLanguages (SML) 38 Recursive Functions Recursionis thenormin ML- funfactn == if n=0then1 elsen * fact(n-1);valfact= fn : int-> int- fact7;valit = 5040: int Tailrecursive functionsmoree cient- funfacti(n,p)== if n=0thenp elsefacti(n-1,n*p);valfacti= fn : int* int-> int ButnotnecessarilypracticalProgrammingLan guages|Lecture3 |FunctionalLanguages (SML) 39 IntegerListQuickSortlocalfunpartition(pi vot,nil)= (nil,nil)| partition(pivot,h :: t) =letval(smalls,bigs)= partition(pivot,t)inif h < pivotthen(h :: smalls,bigs)else(smalls,h :: bigs)end;infunqsortnil= nil| qsort[singleton]= [singleton]| qsort(h :: t) =letval(smalls,bigs)= partition(h,t)in qsort(smalls)@ [h]@ qsort(bigs)end;end;ProgrammingLanguages| Lecture3 |FunctionalLanguages (SML) 40 PolymorphicQuicksortlocalfunpartition(pi vot,nil)(lessThan)= (nil,nil)| partition(pivot,first:: others)(lessThan)=letval(smalls,bigs)= partition(pivot,others)(lessThan)inif (lessThanfirstpivot)then(first::smalls,b igs)else(smalls,first::bigs)end;infunqso rtnillessThan= nil| qsort[singleton]lessThan= [singleton]| qsort(first::rest)lessThan=letval(smalls ,bigs)= partition(first,rest)lessThanin(qsortsma llslessThan)@ [first]@ (qsortbigslessThan)end;end.

8 ProgrammingLanguages|Lecture3 |FunctionalLanguages (SML) 41 UsingPolymorphicQuickSort De necomparisonfunctionfunintLt(x:int)y = x < y; Mustbe curried:(why?)valintLt= fn : int-> int-> bool Application- qsort[9,1,6,3,4,7,5,8,2,10]intLt;valit = [1,2,3,4,5,6,7,8,9,10] : intlistProgrammingLanguages|Lecture3 |FunctionalLanguages (SML) 42 Fibonacci ObviousFibonaccifunctionslow Iterative solutionfasterintfastfib(intn) {inta = 1, b = 1;while(n > 0) {a = b; b = a + b; n--;(* couldbe parallel*)}returna;} Equivalent MLfunfastfibn : int=letfunfibLoopa b 0 = a| fibLoopa b n:int= fibLoopb (a+b)(n-1)in fibLoop1 1 nend;ProgrammingLanguages|Lecture3 |FunctionalLanguages (SML) 43 DeclaringTypes typede nesa newnamefora type- typeusername= { name:string,userid:int};typeusername= {name:string,userid:int} May be neededto constrainfunctiontypes- funnmeuser= #nameuser; :unresolvedflexrecord(can'ttellwhatfield stherearebesides#name)- funnme(user:username)= #nameuser;valnme= fn : username-> string A polymorphictypetype'a pair= 'a * 'aProgrammingLanguages|Lecture3 |FunctionalLanguages (SML) 44 ConcreteDataTypes Ways of declaringtypes of datastructures Enumeratedtypesdatatypeulevel=Freshman| Soph| Junior| Senior;datatypeglevel= MS | PhD; Moregeneraltypesdatatypestudent= Undergradof ulevel;| Gradof int* glevel; UndergradandGradareconstructorsProgrammi ngLanguages|Lecture3 |FunctionalLanguages (SML) 45 PatternMatching FunctionsfunlevelUndergrad(_)= "Anundergrad"| levelGrad(_,MS)= "AnMS student"| levelGrad(_,PhD)= "A PhDstudent" CaseExpressions(cases ofUndergrad(_)= "Anundergrad"| Grad(_,MS)= "AnMS student"| Grad(_,PhD)= "A PhDstudent")ProgrammingLanguages| Lecture 3 |FunctionalLanguages (SML) 46 Recursive Types Cande netypes thatuseeach other- datatypes = a of t= andt = b of s | c;datatypes = a of tdatatypet = b of s | c- a(b(ac)).

9 Valit = a (b (a c)): s Usefulwhenhave two types thatcancontaintheotherProgrammingLanguag es|Lecture3 |FunctionalLanguages (SML) 47 PolymorphicTypes Nameof type precededby a type variabledatatype'a notmuch= Nothing| Somethingof 'a;datatype('a,'b)sum= In1of 'a | In2of 'b; To usejustuseconstructorsandsomevalue- In11;valit = In11 : (int,'a)sum- Something"me";valit = Something"me": stringnotmuchProgrammingLanguages|Lectur e3 |FunctionalLanguages (SML) 48 Aside:StructureSharing Updatingof datastructuresusessharing- funupdatehdnh [] = [nh]| updatehdnh (h::t)= nh :: t;= valupdatehd= fn : 'a -> 'a list-> 'a list- vall = [1,2,3];vall = [1,2,3]: intlist- vall2 = updatehd2 l;vall2 = [2,2,3]: intlist- l;valit = [1,2,3]: intlist Sharingsafebecauseof updatepolicyProgrammingLanguages| Lecture 3 |FunctionalLanguages (SML) 49 Exceptions Changesorderof execution(usedif errordetected) Declarationlike datatypeexceptionFailedMiserably;excepti onBadBadManof string; Raising/throwingexceptionsraiseFailedMis erably; Catching/handlingexceptionsbadcall("jimm y")handleFailedMiserably=> 0| BadBadMan(s)=> 1;ProgrammingLanguages|Lecture3 |FunctionalLanguages (SML) 50 Lazyvs EagerEvaluation Orderof Operations:{Eager| Evaluateoperand,substitutevalueforformal parameter,andevaluateexpression.}

10 {Lazy|Substituteoperandforformalparamete r,evaluateexpression,evaluateparameteron lywhenvalueis needed. Lazyevaluationalsocalledcall-by-needorno rmalorderevaluation In lazyevaluationeach actualparametereithernever evaluatedor |Lecture3 |FunctionalLanguages (SML) 51 Lazyvs EagerExample Functionfuntest(x:{a:int,b:unit})=if (#a{a=2,b=print("A")}= 2)then(#ax)else(#ax); Evaluationtest{a = 7, b = print("B")}; Eagerevaluation:BA valit = 7 : int Lazyevaluation:AB valit = 7 : intProgrammingLanguages|Lecture3 |FunctionalLanguages (SML) 52In niteLists Functiongeneratesrestof listfunfromn = n :: from(n+1)valnats= from1 Restof listcomputedas needed(inlazydialectof ML)funnth(1,fst::rest)= fst| nth(n,fst::rest)= nth(n-1,rest) nth10 natsbuildslistupto 10 ProgrammingLanguages|Lecture3 |FunctionalLanguages (SML) 53 Why Not? Why notuselazyevaluation? Eagerlanguageeasierandmoree cient to implement (withcurrent technology) If languagehasside-e ects,di cultto know whentheywilloccur Many optimizationsintroduceside-e ects For concurrent executionoftenbetterto}


Related search queries