+ = f(x)
Python Functional Programming
+ 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
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 state and mutable data". In other words, functional programming promotes code with no side effects, no change of value in
change of state”.
Python Functional Programming
What this means?
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).
in their inputs, there is not “environment”.
Python Functional Programming
What are the advantages?
follow the change of state to comprehend what a function, a, method, a class, a whole project works.
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".
Python Functional Programming
Advantages enabled by referential transparence
○ Cache results for previous function calls.
○ Same results regardless how many times you call a function.
○ 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.
○ Functions are isolated, they only depend on their input and their output, so they are very easy to debug.
Python Functional Programming
Advantages enabled by referential transparence
○ Functions calls are independent. ○ We can parallelize in different process/CPUs/computers/… We can execute func1 and func2 in paralell because a won’t be modified.
result = func1(a, b) + func2(a, c)
Python Functional Programming
Advantages enabled by referential transparence
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.
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.
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)
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]
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())
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)
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]
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]
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
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"]]
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
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
Python Functional Programming
Eager vs Lazy Evaluation
assined, function called...
○ 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.
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.
recursion is the function itself.
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
Python Functional Programming
FP in OOP?
It is possible do FP in OOP? Yes it is!
○ 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.
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: Functional:
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 sum(filter(lambda x: x**2 % 5 == 0, range(1, 100))[:10])
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:
Python Functional Programming
Conclusion
you to it.
Actually it will make it more thread-safe also.
lambdas, closures, iterators and generators, also from the modules functools and itertools.
Recursion.
to use recursion.
Python Functional Programming
References
Python Functional Programming
Contact me
○ geisonfgf@gmail.com
○ geisonfgf
○ http://www.facebook.com/geisonfgf
○ http://www.twitter.com/geisonfgf