f x
play

+ f(x) = Python Functional Programming Python Functional - PowerPoint PPT Presentation

+ f(x) = Python Functional Programming Python Functional Programming Functional Programming by Wikipidia: Functional programming is a programming paradigm that treats computation as the evaluation of mathematical functions and avoids


  1. + f(x) = Python Functional Programming

  2. Python Functional Programming Functional Programming by Wikipidia: “Functional programming is a programming paradigm that treats computation as the evaluation of mathematical functions and avoids state and mutable data". In other words, functional programming promotes code with no side effects, no change of value in variables. It oposes to imperative programming, which enfatizes change of state”.

  3. Python Functional Programming What this means? ● No mutable data (no side effect). ● No state (no implicit, hidden state). Once assigned (value binding), a variable (a symbol) does not change its value. All state is bad? No, hidden , implicit state is bad. Functional programming do not eliminate state, it just make it visible and explicit (at least when programmers want it to be). ● Functions are pure functions in the mathematical sense: their output depend only in their inputs, there is not “environment”. ● Same result returned by functions called with the same inputs.

  4. Python Functional Programming What are the advantages? ● Cleaner code: "variables" are not modified once defined, so we don't have to follow the change of state to comprehend what a function, a, method, a class, a whole project works. ● Referential transparency: Expressions can be replaced by its values. If we call a function with the same parameters, we know for sure the output will be the same (there is no state anywhere that would change it). There is a reason for which Einstein defined insanity as "doing the same thing over and over again and expecting different results" .

  5. Python Functional Programming Advantages enabled by referential transparence ● Memoization ○ Cache results for previous function calls. ● Idempotence ○ Same results regardless how many times you call a function. ● Modularization ○ We have no state that pervades the whole code, so we build our project with small, black boxes that we tie together, so it promotes bottom-up programming. ● Ease of debugging ○ Functions are isolated, they only depend on their input and their output, so they are very easy to debug.

  6. Python Functional Programming Advantages enabled by referential transparence ● Parallelization ○ Functions calls are independent. ○ We can parallelize in different process/CPUs/computers/ … result = func1(a, b) + func2(a, c) We can execute func1 and func2 in paralell because a won’t be modified.

  7. Python Functional Programming Advantages enabled by referential transparence ● Concurrence a. With no shared data, concurrence gets a lot simpler: i. No semaphores. ii. No monitors. iii. No locks. iv. No race-conditions. v. No dead-locks.

  8. Python Functional Programming Python is a multi paradigm programming language. As a Python programmer why uses functional programming in Python? Python is not a functional language but have a lot of features that enables us to applies functional principles in the development, turning our code more elegant, concise, maintanable, easier to understand and test.

  9. Python Functional Programming Don’t Update, Create - String name = 'Geison' name = '{0} Flores'.format(name) FIRSTNAME = 'Geison' LASTNAME = '{0} Flores'.format(FIRSTNAME) NAME = '{0} {1}'.format(FIRSTNAME, LASTNAME)

  10. Python Functional Programming Don’t Update, Create - Lists years = [2001, 2002] years.append(2003) years += [2004, 2005] years # [2001, 2002, 2003, 2004, 2005] YEARS = [2001, 2001] ALL_YEARS = YEARS + [2003] + [2004, 2005]

  11. Python Functional Programming Don’t Update, Create - Dict ages = {'John': 30} ages['Mary'] = 28 ages # {'John': 30, 'Mary': 28} AGES = {'John': 30} ALL_AGES = dict(AGES.itens() + {'Mary': 28}.itens())

  12. Python Functional Programming Higher Order Functions Functions and methods are first-class objects in Python, so if you want to pass a function to another function, you can just treat it as any other object. def caller(f): f() def say_hello(name): return 'Hello {0}'.format(name) caller(say_hello)

  13. Python Functional Programming Higher Order Functions - Map map(lambda word: word.upper(), ["milu", "rantanplan"]) # result ["MILU", "RANTANPLAN"] def add_2(n): n + 2 map(add_2, [1, 2, 3]) # result [3, 4, 5]

  14. Python Functional Programming Higher Order Functions - Filter filter(lambda word: len(word) == 4, ["milu", "rantanplan"]) # result ["MILU"] def greater_than_10(num): return num > 10 filter(greater_than_10, range(15)) # result [11, 12, 13, 14, 15]

  15. Python Functional Programming Higher Order Functions - Reduce import operator reduce(operator.add, [1, 2, 3, 4, 5]) # result 15 def acumullator(a, b): return len(a) + len(b) reduce(acumullator, ["milu", "rantanplan"]) # result 14 reduce(lambda a,b: len(a) + len(b), ["milu", "rantanplan"]) # result 14

  16. Python Functional Programming Higher Order Functions - Reduce from itertools import izip list1 = [1, 2, 3] list2 = ["a", "b", "c"] [list(x) for x in izip(list1, list2)] # result [[1, "a"], [2, "b"], [3, "c"]]

  17. Python Functional Programming Higher Order Functions - Closure def add_x(x): def adder(y): return x + y return adder add_5 = add_x(5) add_7 = add_x(7) add_5(10) # result 15 add_7(10) # result 17

  18. Python Functional Programming Currying and Partial Functions Higher-order functions enable Currying , which the ability to take a function that accepts n parameters and turns it into a composition of n functions each of them take 1 parameter. A direct use of currying is the Partial Functions where if you have a function that accepts n parameters then you can generate from it one of more functions with some parameter values already filled in. from functools import partial plus = lambda a, b: a + b # defining a function that sums 2 numbers plus(3, 5) # result 8 # curring calling partial function by supplying the first parameters with value 1 plus_one = partial(plus, 1) # I can use the new function as normal plus_one(5) # result 6

  19. Python Functional Programming Eager vs Lazy Evaluation ● Eager evaluation: expressions are calculated at the moment that variables is assined, function called... ● Lazy evaluation: delays the evaluation of the expression until it is needed. ○ Memory efficient: no memory used to store complete structures. ○ CPU efficient: no need to calculate the complete result before returning. ○ Laziness is not a requisite for FP, but it is a strategy that fits nicely on the paradigm(Haskell). Python uses eager evaluation (but short-circuits && or ||). Python generators are a mechanism for lazy evaluation. Python arrays are not lazy, use enumarators when necessary.

  20. Python Functional Programming Recursion Looping by calling a function from within itself. When you don’t have access to mutable data, recursion is used to build up and chain data construction. This is because looping is not a functional concept, as it requires variables to be passed around to store the state of the loop at a given time. ● Purely functional languages have no imperative for-loops, so they use recursion a lot. ● If every recursion created an stack, it would blow up very soon. ● Tail-call optimization (TCO) avoids creating a new stack when the last call in a recursion is the function itself. ● TCO is not implemented in Python. ● Unfortunarely following recursion style in Python has it’s own tax: Performance.

  21. Python Functional Programming Solving Python Lack of TCO(Tail Call Optimization) # The functional solution have problens with big values fib = lambda n: n if n < 2 else fib(n-1) + fib(n-2) # The iterative solution using generators works perfectly with large values def fibs(): a = 0 b = 1 while True: yield a a, b = b, a + b

  22. Python Functional Programming FP in OOP? It is possible do FP in OOP? Yes it is! ● OOP is orthogonal to FP. ● Well, at least in theory, because: ○ Typical OOP tends to emphasize change of state in objects. ○ Typical OOP mixes the concepts of identity and state. ○ Mixture of data and code raises both conceptual and practical problems. ● OOP functional languages: Scala, F#, ...

  23. Python Functional Programming A Pratical Example Exercise: "What's the sum of the first 10 natural number whose square value is divisible by 5?" Imperative: n, num_elements, s = 1, 0, 0 while num_elements < 10: if n**2 % 5 == 0: s += n num_elements += 1 n += 1 n #275 Functional: sum(filter(lambda x: x**2 % 5 == 0, range(1, 100))[:10])

  24. Python Functional Programming The last advice Learn at least one functional language, it will open your mind to a new paradigm becoming you a better programmer. Some Functional Languages: ● Haskell ● ML (Standard ML, Objective Caml, ...) ● Scheme ● Erlang ● Scala ● Closure ● F#

Download Presentation
Download Policy: The content available on the website is offered to you 'AS IS' for your personal information and use only. It cannot be commercialized, licensed, or distributed on other websites without prior consent from the author. To download a presentation, simply click this link. If you encounter any difficulties during the download process, it's possible that the publisher has removed the file from their server.

Recommend


More recommend