Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
PrinciplesofProgramming Languages- 815338A FunctionalProgramming 1-1 Introduction • Thedesignoftheimperativelanguagesisbaseddirectlyonthevon Neumannarchitecture • Efficiencyistheprimaryconcern,ratherthanthesuitabilityofthelanguage forsoftwaredevelopment • Thedesignofthefunctionallanguagesisbasedonmathematical functions • Asolidtheoreticalbasisthatisalsoclosertotheuser,butrelatively unconcernedwiththearchitectureofthemachinesonwhichprogramswill run Copyright © 2012 Addison-Wesley. All rights reserved. 1-2 MathematicalFunctions • Amathematicalfunctionisamapping ofmembersofoneset,called thedomainset,toanotherset,calledtherangeset • Alambdaexpression specifiestheparameter(s)andthemappingofa functioninthefollowingform l(x) x * x * x forthefunctioncube(x) = x * x * x Copyright © 2012 Addison-Wesley. All rights reserved. 1-3 LambdaExpressions • Lambdaexpressionsdescribenamelessfunctions • Lambdaexpressionsareappliedtoparameter(s)byplacingthe parameter(s)aftertheexpression e.g.,(l(x) x * x * x)(2) whichevaluatesto8 Copyright © 2012 Addison-Wesley. All rights reserved. 1-4 FunctionalForms • Ahigher-orderfunction,orfunctionalform,isonethateithertakes functionsasparametersoryieldsafunctionasitsresult,orboth Copyright © 2012 Addison-Wesley. All rights reserved. 1-5 FunctionComposition • Afunctionalformthattakestwofunctionsasparametersandyieldsa functionwhosevalueisthefirstactualparameterfunctionappliedto theapplicationofthesecond Form:h º f ° g whichmeansh (x) º f ( g ( x)) Forf (x) º x + 2 andg (x) º 3 * x, h º f ° g yields(3 * x)+ 2 Copyright © 2012 Addison-Wesley. All rights reserved. 1-6 Apply-to-all • Afunctionalformthattakesasinglefunctionasaparameterandyields alistofvaluesobtainedbyapplyingthegivenfunctiontoeachelement ofalistofparameters Form:a Forh(x) º x * x a(h, (2, 3, 4)) yields(4, 9, 16) Copyright © 2012 Addison-Wesley. All rights reserved. 1-7 FundamentalsofFunctionalProgramming Languages • TheobjectiveofthedesignofaFPListomimicmathematical functionstothegreatestextentpossible • ThebasicprocessofcomputationisfundamentallydifferentinaFPL thaninanimperativelanguage • Inanimperativelanguage,operationsaredoneandtheresultsare storedinvariablesforlateruse • Managementofvariablesisaconstantconcernandsourceof complexityforimperativeprogramming • InanFPL,variablesarenotnecessary,asisthecaseinmathematics • ReferentialTransparency- InanFPL,theevaluationofafunction alwaysproducesthesameresultgiventhesameparameters Copyright © 2012 Addison-Wesley. All rights reserved. 1-8 LISPDataTypesandStructures • Dataobjecttypes:originallyonlyatomsandlists • Listform:parenthesizedcollectionsofsublistsand/oratoms e.g.,(A B (C D) E) • Originally,LISPwasatypelesslanguage • LISPlistsarestoredinternallyassingle-linkedlists Copyright © 2012 Addison-Wesley. All rights reserved. 1-9 LISPInterpretation • Lambdanotationisusedtospecifyfunctionsandfunction definitions.Functionapplicationsanddatahavethesameform. e.g.,Ifthelist(A B C) isinterpretedasdataitis asimplelistofthreeatoms,A,B,andC Ifitisinterpretedasafunctionapplication, itmeansthatthefunctionnamedA is appliedtothetwoparameters,B andC • ThefirstLISPinterpreterappearedonlyasademonstrationofthe universalityofthecomputationalcapabilitiesofthenotation Copyright © 2012 Addison-Wesley. All rights reserved. 1-10 OriginsofScheme • Amid-1970sdialectofLISP,designedtobeacleaner,moremodern, andsimplerversionthanthecontemporarydialectsofLISP • Usesonlystaticscoping • Functionsarefirst-classentities • Theycanbethevaluesofexpressionsandelementsoflists • Theycanbeassignedtovariables,passedasparameters,andreturnedfrom functions Copyright © 2012 Addison-Wesley. All rights reserved. 1-11 TheSchemeInterpreter • Ininteractivemode,theSchemeinterpreterisaninfinitereadevaluate-printloop(REPL) • ThisformofinterpreterisalsousedbyPythonandRuby • ExpressionsareinterpretedbythefunctionEVAL • Literalsevaluatetothemselves Copyright © 2012 Addison-Wesley. All rights reserved. 1-12 PrimitiveFunctionEvaluation • • • • Parametersareevaluated,innoparticularorder Thevaluesoftheparametersaresubstitutedintothefunction body Thefunctionbodyisevaluated Thevalueofthelastexpressioninthebodyisthevalueofthe function Copyright © 2012 Addison-Wesley. All rights reserved. 1-13 PrimitiveFunctions&LAMBDA Expressions • PrimitiveArithmeticFunctions:+,-,*,/,ABS,SQRT,REMAINDER, MIN,MAX e.g.,(+ 5 2) yields7 • LambdaExpressions • Formisbasedonl notation e.g.,(LAMBDA (x) (* x x) x iscalledaboundvariable • Lambdaexpressionscanbeappliedtoparameters e.g.,((LAMBDA (x) (* x x)) 7) • LAMBDA expressionscanhaveanynumberofparameters (LAMBDA (a b x) (+ (* a x x) (* b x))) Copyright © 2012 Addison-Wesley. All rights reserved. 1-14 SpecialFormFunction:DEFINE • DEFINE - Twoforms: 1. Tobindasymboltoanexpression e.g.,(DEFINE pi 3.141593) Exampleuse:(DEFINE two_pi (* 2 pi)) Thesesymbolsarenotvariables– theyarelikethenamesboundbyJava’s final declarations 2. Tobindnamestolambdaexpressions(LAMBDA isimplicit) e.g.,(DEFINE (square x) (* x x)) Exampleuse:(square 5) - TheevaluationprocessforDEFINE isdifferent!Thefirstparameter isneverevaluated.Thesecondparameterisevaluatedandboundto thefirstparameter. Copyright © 2012 Addison-Wesley. All rights reserved. 1-15 OutputFunctions • Usuallynotneeded,becausetheinterpreteralwaysdisplaysthe resultofafunctionevaluatedatthetoplevel(notnested) • SchemehasPRINTF,whichissimilartotheprintf functionof C • Note:explicitinputandoutputarenotpartofthepurefunctional programmingmodel,becauseinputoperationschangethestateof theprogramandoutputoperationsaresideeffects Copyright © 2012 Addison-Wesley. All rights reserved. 1-16 NumericPredicateFunctions • #T (or#t)istrueand#F (or#f)isfalse(sometimes() isusedfor false) • =,<>,>,<,>=,<= • EVEN?,ODD?,ZERO?,NEGATIVE? • TheNOT functioninvertsthelogicofaBooleanexpression Copyright © 2012 Addison-Wesley. All rights reserved. 1-17 ControlFlow • Selection- thespecialform,IF (IF predicatethen_expelse_exp) (IF (<> count 0) (/ sum count) ) • RecallfromChapter8theCOND function: (DEFINE (leap? year) (COND ((ZERO? (MODULO year 400)) #T) ((ZERO? (MODULO year 100)) #F) (ELSE (ZERO? (MODULO year 4))) )) Copyright © 2012 Addison-Wesley. All rights reserved. 1-18 ListFunctions QUOTE - takesoneparameter;returnstheparameter • • • withoutevaluation QUOTE isrequiredbecausetheSchemeinterpreter,namedEVAL, alwaysevaluatesparameterstofunctionapplicationsbefore applyingthefunction.QUOTE isusedtoavoidparameter evaluationwhenitisnotappropriate QUOTE canbeabbreviatedwiththeapostropheprefixoperator '(A B) isequivalentto(QUOTE (A B)) Copyright © 2012 Addison-Wesley. All rights reserved. 1-19 ExampleSchemeFunction:member • member takesanatomandasimplelist;returns#T iftheatomis inthelist;#F otherwise DEFINE (member atm a_list) (COND ((NULL? a_list) #F) ((EQ? atm (CAR lis)) #T) ((ELSE (member atm (CDR a_list))) )) Copyright © 2012 Addison-Wesley. All rights reserved. 1-20 ExampleSchemeFunction:equalsimp • equalsimp takestwosimplelistsasparameters;returns#T if thetwosimplelistsareequal;#F otherwise (DEFINE (equalsimp list1 list2) (COND ((NULL? list1) (NULL? list2)) ((NULL? list2) #F) ((EQ? (CAR list1) (CAR list2)) (equalsimp(CDR list1)(CDR list2))) (ELSE #F) )) Copyright © 2012 Addison-Wesley. All rights reserved. 1-21 ExampleSchemeFunction:equal • equal takestwogenerallistsasparameters;returns#T ifthe twolistsareequal;#F otherwise (DEFINE (equal list1 list2) (COND ((NOT (LIST? list1))(EQ? list1 list2)) ((NOT (LIST? lis2)) #F) ((NULL? list1) (NULL? list2)) ((NULL? list2) #F) ((equal (CAR list1) (CAR list2)) (equal (CDR list1) (CDR list2))) (ELSE #F) )) Copyright © 2012 Addison-Wesley. All rights reserved. 1-22 ExampleSchemeFunction:append • append takestwolistsasparameters;returnsthefirst parameterlistwiththeelementsofthesecondparameter listappendedattheend (DEFINE (append list1 list2) (COND ((NULL? list1) list2) (ELSE (CONS (CAR list1) (append (CDR list1) list2))) )) Copyright © 2012 Addison-Wesley. All rights reserved. 1-23 ExampleSchemeFunction:LET • RecallthatLET wasdiscussedinChapter5 • LET isactuallyshorthandforaLAMBDA expressionappliedtoa parameter (LET ((alpha 7))(* 5 alpha)) isthesameas: ((LAMBDA (alpha) (* 5 alpha)) 7) Copyright © 2012 Addison-Wesley. All rights reserved. 1-24 LET Example (DEFINE (quadratic_roots a b c) (LET ( (root_part_over_2a (/ (SQRT (- (* b b) (* 4 a c)))(* 2 a))) (minus_b_over_2a (/ (- 0 b) (* 2 a))) (LIST (+ minus_b_over_2a root_part_over_2a)) (- minus_b_over_2a root_part_over_2a)) )) Copyright © 2012 Addison-Wesley. All rights reserved. 1-25 TailRecursioninScheme • Definition:Afunctionistailrecursiveifitsrecursivecallisthelast operationinthefunction • Atailrecursivefunctioncanbeautomaticallyconvertedbyacompiler touseiteration,makingitfaster • SchemelanguagedefinitionrequiresthatSchemelanguagesystems convertalltailrecursivefunctionstouseiteration Copyright © 2012 Addison-Wesley. All rights reserved. 1-26 TailRecursioninScheme- continued • Exampleofrewritingafunctiontomakeittailrecursive,usinghelperafunction Original:(DEFINE (factorial n) (IF (<= n 0) 1 (* n (factorial (- n 1))) )) Tailrecursive: (DEFINE (facthelper n factpartial) (IF (<= n 0) factpartial facthelper((- n 1) (* n factpartial))) )) (DEFINE (factorial n) (facthelper n 1)) Copyright © 2012 Addison-Wesley. All rights reserved. 1-27 FunctionalForm- Composition • Composition • Ifh isthecompositionoff andg,h(x) = f(g(x)) (DEFINE (g x) (* 3 x)) (DEFINE (f x) (+ 2 x)) (DEFINE h x) (+ 2 (* 3 x))) (Thecomposition) • InScheme,thefunctionalcompositionfunctioncompose canbe written: (DEFINE (compose f g) (LAMBDA (x) (f (g x)))) ((compose CAR CDR) '((a b) c d)) yieldsc (DEFINE (third a_list) ((compose CAR (compose CDR CDR)) a_list)) isequivalenttoCADDR Copyright © 2012 Addison-Wesley. All rights reserved. 1-28 FunctionalForm– Apply-to-All • ApplytoAll- oneforminSchemeismap • Appliesthegivenfunctiontoallelementsofthegivenlist; (DEFINE (map fun a_list) (COND ((NULL? a_list) '()) (ELSE (CONS (fun (CAR a_list)) (map fun (CDR a_list)))) )) (map (LAMBDA (num) (* num num num)) '(3 4 2 6)) yields (27 64 8 216) Copyright © 2012 Addison-Wesley. All rights reserved. 1-29 FunctionsThatBuildCode • ItispossibleinSchemetodefineafunctionthatbuildsSchemecode andrequestsitsinterpretation • Thisispossiblebecausetheinterpreterisauser-availablefunction, EVAL Copyright © 2012 Addison-Wesley. All rights reserved. 1-30 AddingaListofNumbers ((DEFINE (adder a_list) (COND ((NULL? a_list) 0) (ELSE (EVAL (CONS '+ a_list))) )) • Theparameterisalistofnumberstobeadded;adder insertsa+ operatorandevaluatestheresultinglist • UseCONS toinserttheatom+ intothelistofnumbers. • Besurethat+ isquotedtopreventevaluation • SubmitthenewlisttoEVAL forevaluation Copyright © 2012 Addison-Wesley. All rights reserved. 1-31 CommonLISP • Acombinationofmanyofthefeaturesofthepopular dialectsofLISParoundintheearly1980s • Alargeandcomplexlanguage--theoppositeofScheme • Featuresinclude: • • • • • • • records arrays complexnumbers characterstrings powerfulI/Ocapabilities packageswithaccesscontrol iterativecontrolstatements Copyright © 2012 Addison-Wesley. All rights reserved. 1-32 CommonLISP(continued) • Macros • Createtheireffectintwosteps: • Expandthemacro • Evaluatetheexpandedmacro • SomeofthepredefinedfunctionsofCommonLISPareactually macros • UserscandefinetheirownmacroswithDEFMACRO Copyright © 2012 Addison-Wesley. All rights reserved. 1-33 CommonLISP(continued) • Backquoteoperator(`) • SimilartotheScheme’sQUOTE,exceptthatsomepartsoftheparameter canbeunquotedbyprecedingthemwithcommas `(a (* 3 4) c) evaluatesto(a (* 3 4) c) `(a ,(* 3 4) c) evaluatesto(a 12 c) Copyright © 2012 Addison-Wesley. All rights reserved. 1-34 CommonLISP(continued) • ReaderMacros • LISPimplementationshaveafrontendcalledthereader thattransforms LISPintoacoderepresentation.Thenmacrocallsareexpandedintothe coderepresentation. • Areadermacroisaspecialkindofmacrothatisexpandedduringthe readerphase • Areadermacroisadefinitionofasinglecharacter,whichisexpanded intoitsLISPdefinition • Anexampleofareadermacroisanapostrophecharacter,whichis expandedintoacalltoQUOTE • Userscandefinetheirownreadermacrosasakindofshorthand Copyright © 2012 Addison-Wesley. All rights reserved. 1-35 CommonLISP(continued) • CommonLISPhasasymboldatatype(similartothatofRuby) • Thereservedwordsaresymbolsthatevaluatetothemselves • Symbolsareeitherboundorunbound • Parametersymbolsareboundwhilethefunctionisbeingevaluated • Symbolsthatarethenamesofimperativestylevariablesthathavebeenassignedvalues arebound • Allothersymbolsareunbound Copyright © 2012 Addison-Wesley. All rights reserved. 1-36 ML • Astatic-scopedfunctionallanguagewithsyntaxthatiscloserto PascalthantoLISP • Usestypedeclarations,butalsodoestypeinferencing to determinethetypesofundeclaredvariables • Itisstronglytyped(whereasSchemeisessentiallytypeless)and hasnotypecoercions • Doesnothaveimperative-stylevariables • Itsidentifiersareuntypednamesforvalues • Includesexceptionhandlingandamodulefacilityfor implementingabstractdatatypes • Includeslistsandlistoperations Copyright © 2012 Addison-Wesley. All rights reserved. 1-37 MLSpecifics • Atablecalledtheevaluationenvironmentstoresthenamesof allidentifiersinaprogram,alongwiththeirtypes(likearuntimesymboltable) • Functiondeclarationform: fun name (formalparameters) = expression; e.g.,fun cube(x : int) = x * x * x; - Thetypecouldbeattachedtoreturnvalue,asin fun cube(x) : int = x * x * x; - Withnotypespecified,itwoulddefaultto int (thedefaultfornumericvalues) - User-definedoverloadedfunctionsarenotallowed,soifwe wantedacube functionforrealparameters,itwouldneedto haveadifferentname Copyright © 2012 Addison-Wesley. All rights reserved. 1-38 MLSpecifics(continued) • MLselection if expression then then_expression else else_expression wherethefirstexpressionmustevaluatetoaBooleanvalue • Patternmatchingisusedtoallowafunctiontooperateondifferent parameterforms fun fact(0) = 1 | fact(1) = 1 | fact(n : int) : int = n * fact(n – 1) Copyright © 2012 Addison-Wesley. All rights reserved. 1-39 MLSpecifics(continued) • Lists Literallistsarespecifiedinbrackets [3, 5, 7] [] istheemptylist CONS isthebinaryinfixoperator,:: 4 :: [3, 5, 7],whichevaluatesto[4, 3, 5, 7] CAR istheunaryoperatorhd CDR istheunaryoperatortl fun length([]) = 0 | length(h :: t) = 1 + length(t); fun append([], lis2) = lis2 | append(h :: t, lis2) = h :: append(t, lis2); Copyright © 2012 Addison-Wesley. All rights reserved. 1-40 MLSpecifics(continued) • Theval statementbindsanametoavalue(similartoDEFINE in Scheme) val distance = time * speed; • AsisthecasewithDEFINE,val isnothinglikeanassignment statementinanimperativelanguage • Iftherearetwoval statementsforthesameidentifier,thefirstis hiddenbythesecond • val statementsareoftenusedinlet constructs let val radius = 2.7 val pi = 3.14159 in pi * radius * radius end; Copyright © 2012 Addison-Wesley. All rights reserved. 1-41 MLSpecifics(continued) • filter • Ahigher-orderfilteringfunctionforlists • Takesapredicatefunctionasitsparameter,oftenintheformofalambda expression • Lambdaexpressionsaredefinedlikefunctions,exceptwiththereserved wordfn filter(fn(x) => x < 100, [25, 1, 711, 50, 100]); Thisreturns[25, 1, 50] Copyright © 2012 Addison-Wesley. All rights reserved. 1-42 MLSpecifics(continued) • map • Ahigher-orderfunctionthattakesasingleparameter,afunction • Appliestheparameterfunctiontoeachelementofalistandreturnsalistof results fun cube x = x * x * x; val cubeList = map cube; val newList = cubeList [1, 3, 5]; ThissetsnewList to[1, 27, 125] - Alternative:usealambdaexpression val newList = map (fn x => x * x * x, [1, 3, 5]); Copyright © 2012 Addison-Wesley. All rights reserved. 1-43 MLSpecifics(continued) • FunctionComposition • Usetheunaryoperator,o val h = g o f; Copyright © 2012 Addison-Wesley. All rights reserved. 1-44 MLSpecifics(continued) • Currying • MLfunctionsactuallytakejustoneparameter—ifmorearegiven,it considerstheparametersatuple(commasrequired) • Processofcurrying replacesafunctionwithmorethanoneparameter withafunctionwithoneparameterthatreturnsafunctionthattakes theotherparametersoftheoriginalfunction • AnMLfunctionthattakesmorethanoneparametercanbedefinedin curriedformbyleavingoutthecommasintheparameters fun add a b = a + b; Afunctionwithoneparameter,a.Returnsafunctionthattakesb asa parameter.Call:add 3 5; Copyright © 2012 Addison-Wesley. All rights reserved. 1-45 MLSpecifics(continued) • PartialEvaluation • Curriedfunctionscanbeusedtocreatenewfunctionsbypartialevaluation • Partialevaluationmeansthatthefunctionisevaluatedwithactualparameters foroneormoreoftheleftmostactualparameters fun add5 x add 5 x; Takestheactualparameter5 andevaluatestheadd functionwith5 asthe valueofitsfirstformalparameter.Returnsafunctionthatadds5 toitssingle parameter val num = add5 10; (* sets num to 15 *) Copyright © 2012 Addison-Wesley. All rights reserved. 1-46 Haskell • SimilartoML(syntax,staticscoped,stronglytyped,typeinferencing,pattern matching) • DifferentfromML(andmostotherfunctionallanguages)inthatitispurely functional(e.g.,novariables,noassignmentstatements,andnosideeffects ofanykind) SyntaxdifferencesfromML fact 0 = 1 fact 1 = 1 fact n = n * fact (n – 1) fib 0 = 1 fib 1 = 1 fib (n + 2) = fib (n + 1) + fib n Copyright © 2012 Addison-Wesley. All rights reserved. 1-47 FunctionDefinitionswithDifferentParameter Ranges fact | | | sub | | | n n == 0 = 1 n == 1 = 1 n > 0 = n * fact(n – 1) n n < 10 = 0 n > 100 = 2 otherwise = 1 square x = x * x - BecauseHaskellsupportpolymorphism,this worksforanynumerictypeofx Copyright © 2012 Addison-Wesley. All rights reserved. 1-48 HaskellLists • Listnotation:Putelementsinbrackets e.g.,directions = ["north", "south", "east", "west"] • Length:# e.g.,#directions is 4 • Arithmeticserieswiththe.. operator e.g.,[2, 4..10] is [2, 4, 6, 8, 10] • Catenationiswith++ e.g.,[1, 3] ++ [5, 7] resultsin[1, 3, 5, 7] • CONS,CAR,CDR viathecolonoperator e.g.,1:[3, 5, 7] resultsin[1, 3, 5, 7] Copyright © 2012 Addison-Wesley. All rights reserved. 1-49 Haskell(continued) • PatternParameters product [] = 1 product (a:x) = a * product x • Factorial: fact n = product [1..n] • ListComprehensions(Chapter6) [n * n * n | n <- [1..50]] Thequalifierinthisexamplehastheformofagenerator.It couldbeintheformofatest factors n = [i | i <- [1..n `div` 2], n `mod` i == 0] Thebackticksspecifythefunctionisusedasabinaryoperator Copyright © 2012 Addison-Wesley. All rights reserved. 1-50 Quicksort sort [] = [] sort (h:t) = sort [b | b ← t; b <= h] ++ [h] ++ sort [b | b ← t; b > h] IllustratestheconcisionofHaskell Copyright © 2012 Addison-Wesley. All rights reserved. 1-51 LazyEvaluation • Alanguageisstrict ifitrequiresallactualparameterstobefully evaluated • Alanguageisnonstrict ifitdoesnothavethestrictrequirement • Nonstrictlanguagesaremoreefficientandallowsomeinteresting capabilities– infinitelists • Lazyevaluation- Onlycomputethosevaluesthatarenecessary • Positivenumbers positives = [0..] • Determiningif16 isasquarenumber member [] b = False member(a:x) b=(a == b)||member x b squares = [n * n | n ← [0..]] member squares 16 Copyright © 2012 Addison-Wesley. All rights reserved. 1-52 MemberRevisited • Thememberfunctioncouldbewrittenas: member b [] = False member b (a:x)=(a == b) || member b x • However,thiswouldonlyworkiftheparametertosquares wasaperfectsquare;ifnot,itwillkeepgeneratingthem forever.Thefollowingversionwillalwayswork: member2 n (m:x) | m < n = member2 n x | m == n = True | otherwise = False Copyright © 2012 Addison-Wesley. All rights reserved. 1-53 F# • BasedonOcaml,whichisadescendantofMLandHaskell • Fundamentallyafunctionallanguage,butwithimperative featuresandsupportsOOP • Hasafull-featuredIDE,anextensivelibraryofutilities,and interoperateswithother.NETlanguages • Includestuples,lists,discriminatedunions,records,and bothmutableandimmutablearrays • Supportsgenericsequences,whosevaluescanbecreated withgeneratorsandthroughiteration Copyright © 2012 Addison-Wesley. All rights reserved. 1-54 F#(continued) • Sequences let x = seq {1..4};; • Generationofsequencevaluesislazy let y = seq {0..10000000};; Setsy to[0; 1; 2; 3;…] • Defaultstepsizeis1,butitcanbeanynumber let seq1 = seq {1..2..7} Sets seq1 to[1; 3; 5; 7] • Iterators– notlazyforlistsandarrays let cubes = seq {for i in 1..4 -> (i, i * i * i)};; Setscubesto[(1, 1); (2, 8); (3, 27); (4, 64)] Copyright © 2012 Addison-Wesley. All rights reserved. 1-55 F#(continued) • Functions • Ifnamed,definedwithlet;iflambdaexpressions,definedwithfun (fun a b -> a / b) • Nodifferencebetweenanamedefinedwithlet andafunctionwithout parameters • Theextentofafunctionisdefinedbyindentation let f = let pi = 3.14159 let twoPi = 2.0 * pi;; Copyright © 2012 Addison-Wesley. All rights reserved. 1-56 F#(continued) • Functions(continued) • Ifafunctionisrecursive,itsdefinitionmustincludetherec reservedword • Namesinfunctionscanbeoutscoped,whichendstheirscope let x4 = let x = x * x let x = x * x Thefirstlet inthebodyofthefunctioncreatesanewversionofx;this terminatesthescopeoftheparameter;Thesecondlet inthebodycreates anotherx,terminatingthescopeofthesecondx Copyright © 2012 Addison-Wesley. All rights reserved. 1-57 F#(continued) • FunctionalOperators • Pipeline(|>) • Abinaryoperatorthatsendsthevalueofitsleftoperandtothelast parameterofthecall(therightoperand) let myNums = [1; 2; 3; 4; 5] let evensTimesFive = myNums |> List.filter (fun n -> n % 2 = 0) |> List.map (fun n -> 5 * n) Thereturnvalueis[10; 20] ll • ;lkj; Copyright © 2012 Addison-Wesley. All rights reserved. 1-58 F#(continued) • FunctionalOperators(continued) • Composition(>>) • Buildsafunctionthatappliesitsleftoperandtoagivenparameter(afunction)andthen passestheresultreturnedfromthefunctiontoitsrightoperand(anotherfunction) TheF#expression(f >> g) x isequivalenttothemathematicalexpressiong(f(x)) • CurriedFunctions let add a b = a + b;; let add5 = add 5;; Copyright © 2012 Addison-Wesley. All rights reserved. 1-59 F#(continued) • WhyF#isInteresting: • Itbuildsonpreviousfunctionallanguages • Itsupportsvirtuallyallprogrammingmethodologiesinwidespreadusetoday • Itisthefirstfunctionallanguagethatisdesignedforinteroperabilitywith otherwidelyusedlanguages • Atitsrelease,ithadanelaborateandwell-developedIDEandlibraryofutility software Copyright © 2012 Addison-Wesley. All rights reserved. 1-60 SupportforFunctionalProgramminginPrimarily ImperativeLanguages • Supportforfunctionalprogrammingisincreasinglycreepinginto imperativelanguages • Anonymousfunctions(lambdaexpressions) • JavaScript:leavethenameoutofafunctiondefinition • C#:i => (i % 2) == 0 (returnstrueorfalsedependingonwhetherthe parameterisevenorodd) • Python:lambda a, b : 2 * a - b Copyright © 2012 Addison-Wesley. All rights reserved. 1-61 SupportforFunctionalProgramminginPrimarily ImperativeLanguages(continued) • Pythonsupportsthehigher-orderfunctionsfilterandmap (oftenuselambdaexpressionsastheirfirstparameters) map(lambda x : x ** 3, [2, 4, 6, 8]) Returns[8, 64, 216, 512] • Pythonsupportspartialfunctionapplications from operator import add add5 = partial (add, 5) (thefirstlineimportsadd asafunction) Use:add5(15) Copyright © 2012 Addison-Wesley. All rights reserved. 1-62 SupportforFunctionalProgramminginPrimarily ImperativeLanguages(continued) • RubyBlocks • Areeffectivelysubprogramsthataresenttomethods,whichmakesthe methodahigher-ordersubprogram • Ablockcanbeconvertedtoasubprogramobjectwithlambda times = lambda {|a, b| a * b} Use:x = times.(3, 4) (setsx to12) • Timescanbecurriedwith times5 = times.curry.(5) Use:x5 = times5.(3) (setsx5 to15) Copyright © 2012 Addison-Wesley. All rights reserved. 1-63 ComparingFunctionalandImperativeLanguages • ImperativeLanguages: • • • • Efficientexecution Complexsemantics Complexsyntax Concurrencyisprogrammerdesigned • FunctionalLanguages: • • • • Simplesemantics Simplesyntax Lessefficientexecution Programscanautomaticallybemadeconcurrent Copyright © 2012 Addison-Wesley. All rights reserved. 1-64 Summary • Functionalprogramminglanguagesusefunctionapplication,conditional expressions,recursion,andfunctionalformstocontrolprogramexecution • LISPbeganasapurelyfunctionallanguageandlaterincludedimperative features • SchemeisarelativelysimpledialectofLISPthatusesstaticscoping exclusively • CommonLISPisalargeLISP-basedlanguage • MLisastatic-scopedandstronglytypedfunctionallanguagethatusestype inference • Haskellisalazyfunctionallanguagesupportinginfinitelistsandset comprehension. • F#isa.NETfunctionallanguagethatalsosupportsimperativeandobjectorientedprogramming • Someprimarilyimperativelanguagesnowincorporatesomesupportfor functionalprogramming • Purelyfunctionallanguageshaveadvantagesoverimperativealternatives, butstillarenotverywidelyused Copyright © 2012 Addison-Wesley. All rights reserved. 1-65