/
LECTURE 42: Functional Programming LECTURE 42: Functional Programming

LECTURE 42: Functional Programming - PowerPoint Presentation

emily
emily . @emily
Follow
66 views
Uploaded On 2023-08-31

LECTURE 42: Functional Programming - PPT Presentation

Objectives Programming Paradigms Simple Functional Ideas Basic F Resources Map Reduce Filter F Cheat Sheet Lambda Calculus Intro to Functional Programming Imperative Object Oriented ID: 1015027

int add var return add int return var list fsharp fun filter functional sum order github lambda array map

Share:

Link:

Embed:

Download Presentation from below link

Download Presentation The PPT/PDF document "LECTURE 42: Functional Programming" is the property of its rightful owner. Permission is granted to download and print the materials on this web site for personal, non-commercial use only, and to display it on your personal computer provided you do not modify the materials and that you retain all copyright notices contained in the materials. By downloading content from our website, you accept the terms of this agreement.


Presentation Transcript

1. LECTURE 42: Functional ProgrammingObjectives: Programming ParadigmsSimple Functional IdeasBasic F# Resources: Map, Reduce, FilterF# Cheat SheetLambda CalculusIntro to Functional Programming

2. ImperativeObject Oriented DeclarativeFunctionalProgramming ParadigmsF#Scheme

3. Fewer BugsCode Simpler/More Maintainable Code No Side EffectsEasy to Parallelize & Scale Mathematically ProvableIts been around a whileWhy Should I Use Functional Programming?

4. Functional Core Concepts

5. Terms to KnowImmutable DataFirst Class FunctionsTail Call OptimizationMappingReducingPipeliningRecursionCurryingHigher Order FunctionsLazy EvaluationMonad: “A Monad is just a monoid in the category of endofunctors, what’s the problem?

6. a = 0b = 2sum = 0def add(): global sum sum = a + bdef add(a, b): return a + bSide EffectsNo Side Effects Functional Programming

7. x = np.random.rand(10,)for i in range(len(x)): y[i] = x[i] * 5 x = np.random.rand(10,)y = map(lambda v : v * 5, filter(lambda u : u % 2, x))ImperativeFunctionalHigher Order FunctionsWhat’s the difference between these?

8. x = np.random.rand(10,)for i in range(len(x)): if(x[i] % 2): y[i] = x[i] * 5 else: y[i] = x[i]x = np.random.rand(10,)y = map(lambda v : v * 5, filter(lambda u : u % 2, x))ImperativeFunctionalHigher Order Functions

9. x = np.random.rand(10,)for i in range(len(x)): if(x[i] % 2): y[i] = x[i] * 5 else: y[i] = x[i]x = np.random.rand(10,)y = map(lambda v : v * 5, filter(lambda u : u % 2, x))ImperativeFunctionalHigher Order Functions

10. x = [0, 1, 2, 3, 4]sum(x)import functoolsx = [0, 1, 2, 3, 4]ans = functools.reduce(lambda a, b: a + b, x) ImperativeFunctional Python 3.5Higher Order Functionsx = [0, 1, 2, 3, 4]ans = reduce(lambda a, b: a + b, x) Functional Python 2.5

11. def factorial(n, r=1) : if n <= 1 : return r else : return factorial(n-1, n*r)def factorial(n): if n==0 : return 1 else : return n * factorial(n-1)Optimized Tail RecursiveTail RecursiveTail Call Recursion

12. Partial FunctionsConsider a function f(a, b, c); Maybe you want a function g(b, c) that’s equivalent to f(1, b, c);This is called “partial function application”.import functoolsdef log(message, subsystem): """Write the contents of 'message' to the specified subsystem.""" print('%s: %s' % (subsystem, message)) ...server_log = functools.partial(log, subsystem='server')server_log('Unable to open socket')

13. What’s Next?

14. Functional Basics with F#

15. F# Syntax Cheat Sheetshttp://dungpa.github.io/fsharp-cheatsheet/http://www.samskivert.com/code/fsharp/fsharp-cheat-sheet.pdfhttps://msdn.microsoft.com/en-us/library/dd233181.aspxhttp://en.wikibooks.org/wiki/F_Sharp_Programming

16. History of F#15F#OCamlC#/.NETSimilar core languageSimilar object model

17. Imperative vs. FunctionalImperative FunctionalC#F#

18. What does “functional” even mean?Preferring immutabilityAvoid state changes, side effects, and mutable data as much as possible. Using data in  data out transformationsTry modeling your problem as a mapping of inputs to outputs. Everything is an expression! Too much |> ignore is often an anti-patternTreating functions as the unit of work, not objectsLooking at problems recursively Think of ways to model a problem as successively smaller chunks of the same problem

19. Functional basics – Immutabilityvar x = 1;let x = 1x++let y = x+1let mutable x = 1x<-2

20. Declarative Style var vipCustomers = customers.Where(c => c.IsVip);var vipCustomers = new List<Customer>();foreach (var customer in customers){ if (customer.IsVip) vipCustomers.Add(customer);}ImperativeDeclarative

21. Functionsint Add(int x, int y){ var z = x + y; return z;} int Add(int x, int y){ var z = x + y; return z;} int Add(int x, int y){ var z = x + y; return z;} Add(x, y){ var z = x + y; return z;} Add(x, y){ var z = x + y; return z;} add(x, y){ var z = x + y; return z;} add(x, y){ var z = x + y; return z;} add x y{ var z = x + y; return z;} let add x y ={ var z = x + y; return z;} let add x y ={ var z = x + y; return z;} let add x y = var z = x + y; return z; let add x y = var z = x + y; return z; let add x y = var z = x + y return zlet add x y = var z = x + y return zlet add x y = let z = x + y return zlet add x y = let z = x + y return zlet add x y = let z = x + y zlet add x y = let z = x + y zlet add x y = let z = x + y zlet add x y = x + y let add x y = x + yint -> int -> intFunc<int,int,int>InOutInOutint Add(int x, int y){ var z = x + y; return z;} int Add(int x, int y){ return x + y;} no typescamel caseno parens and commasno curly bracesno semi colonslet and equalslet instead of varno return

22. Pipeline Operatorlet filteredNumbers = filter (fun n -> n > 1) numberslet filteredNumbers = numbers |> filter (fun n -> n > 1)let filteredNumbers = numbers |> filter (fun n -> n > 1) |> filter (fun n -> n < 3)let filter (condition: int -> bool) (items: int list) = // …

23. Currying//normal versionlet addTwoParameters x y = x + y//explicitly curried versionlet addTwoParameters x = // only one parameter! let subFunction y = x + y // new function with one param subFunction // return the subfunction// now use it step by step let x = 6let y = 99let intermediateFn = addTwoParameters x // return fn with // x "baked in"let result = intermediateFn y // normal versionlet result = addTwoParameters x yval printTwoParameters : int -> (int -> unit)

24. Partial Applicationlet sum a b = a + blet result = sum 1 2 Returns int = 3let result = sum 1Returns int -> intlet addOne = sum 1Returns int -> intlet result = addOne 2Returns int = 3let result = addOne 3Returns int = 4

25. Compositionlet addOne a = a + 1let addTwo a = a + 2let addThree = addOne >> addTwoReturns int = 4let result = addThree 1

26. Functional basics: Higher-order functions[1..10] |> List.filter (fun x -> x % 2 = 0) |> List.map (fun x -> x + 3) |> List.sum[|1.0;2.;3.;4.;5.;6.;7.;8.;9.;10.|] |> Array.filter (fun x -> x % 2. = 0.) |> Array.map (fun x -> x + 3.) |> Array.sumlet sumEvensPlusThree = Array.filter (fun x -> x % 2 = 0) >> Array.map (fun x -> x + 3) >> Array.sumsumEvensPlusThree [|1..10|]let plus_3 x = x + 3let list_plus_3 = List.map plus_3 let filtered = List.filter (fun x -> x % 2 = 0)[1..10] |> filtered |> list_plus_3 |> List.sum[|1..10|] |> sumEvensPlusThree

27. Work with Higher Order FunctionsWhat is the sum of the numbers 1 to 100, each squared?What about the sum of just the even numbers?Write a function that takes any list of floats and a function as an input.Add 10.25 to each elementDivide each element by 4Finally act on the list with the function you sent in.

28. Higher-order functions: Answer

29. The Iterator and Disposable patterns in F#F# provides the use keyword as an equivalent of C#’s using statement keyword (not to be confused with C#’s using directive keyword, whose F# equivalent is open)In F#, seq is provided as a shorthand for IEnumerableYour preference for collections should be (in descending order): list, array, seq

30. What is polymorphism?Subtype polymorphism: when a data type is related to another by substitutabilityParametric polymorphism: when code is written without mention to any specific type (e.g., list of X type, array of X type)Ad hoc polymorphism: when a function can be applied to arguments of different typesOverloading (built-in and/or custom)Haskell: type classesF# specific feature: statically resolved type parameters

31. Continuation Passing Style (a.k.a. Callbacks)“Hey, when you’re done doing that…”Explicitly pass the next thing to doProvides a method of composition of functions that can alter control flowMore common than you may realize (we’ll come back to this…)Very common in Javascript as well

32. Blocking I/O and You – the reason for AsyncThe operating system schedules sequential operations to run in a threadIf code requires external I/O, the thread running that code will block until it is completeThis is bad

33. Example of a blocking operation

34. Your Web Server, Running Blocking I/O

35. Continuation Passing Style (a.k.a. Callbacks)

36. Continuation Pas Style (a.k.a Callback Hell)

37. F# Async to the Rescue!

38.

39. Let’s start from the beginning…

40. Let’s start from the beginning…

41. Let’s start from the beginning…

42. Let’s start from the beginning…Hey, these look like callbacks!

43. Remember …

44. Additional libraries of interestFsCheck: https://github.com/fsharp/FsCheck Canopy: http://lefthandedgoat.github.io/canopy/ FAKE: http://fsharp.github.io/FAKE/ Paket: http://fsprojects.github.io/Paket/ Type Providers: Powershell: http://fsprojects.github.io/FSharp.Management/PowerShellProvider.html FSharp.Data: http://fsharp.github.io/FSharp.Data/ FSharp.Configuration: http://fsprojects.github.io/FSharp.Configuration/

45. General resourcesMe! Team leadsSlack - #fsharp channelF# chat on SOhttp://fsharp.org/ Twitter: #fsharpF# channel on Functional Programming SlackAdditional readingF# for Fun and ProfitF# WeeklyTry F#General Resources & Additional Readings