Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Python con un toque funcional

Python con un toque funcional

Esta presentación fue parte del #13 meetup de Guayaquil Developers

Avatar for Carlos Villavicencio

Carlos Villavicencio

February 20, 2019

Other Decks in Programming

Transcript

  1. Presentación Carlos Villavicencio [email protected] • Software Developer @ StackBuilders •

    Coordinador @ QuitoLambda • @po5i • www.linkedin.com/in/cvillavicencio
  2. Qué es programación funcional? • State-less • Inmutable • Declarativa

    • Sistema de tipos • Funciones de orden superior • Funciones puras
  3. Funciones puras A = 4 def impure_sum(b): return A +

    b def pure_sum(a, b): return a + b impure_sum(6) pure_sum(4, 6)
  4. Funciones como argumento def add(x, y): return x + y

    def calculate(f, x, y): return f(x, y) calculate(add, 5, 5) calculate(lambda x, y: x + y, 5, 5) Expresión λ: Función Anónima
  5. Funciones de orden superior: map new_list = [] for value

    in values: new_list.append(value * 2) new_list = [x * 2 for x in values]
  6. Funciones de orden superior: filter new_list = [] for value

    in values: if value % 2 == 0: new_list.append(value) new_list = [x for x in values if x % 2 == 0]
  7. List comprehensions? list(map(lambda x: x * 2, values)) list(filter(lambda x:

    x % 2 == 0, values)) [x * 2 for x in values] [x for x in values if x % 2 == 0]
  8. Funciones de orden superior: reduce total = 0 for value

    in values: total += value from functools import reduce total = reduce(lambda accum, current: accum + current, values, 0)
  9. Partials def add_two(b): return add(2, b) print(add_two(10)) from functools import

    partial add_two = partial(add, 2) print(add_two(10)) Demo def add(a, b): return a + b
  10. Decorators def say_hello(name): return 'Hello, {}'.format(name) def make_bold(func): def func_wrapper(name):

    return '<strong>{}</strong>'.format(func(name)) return func_wrapper say_hello = make_bold(say_hello) print(say_hello('Chimuelo'))
  11. Decorators (syntactic sugar) def make_bold(func): def func_wrapper(name): return '<strong>{}</strong>'.format(func(name)) return

    func_wrapper @make_bold def say_hello(name): return 'Hello, {}'.format(name) print(say_hello('Chimuelo')) Demo
  12. Generators • “yield” keyword • Retorna un iterador / puede

    ser infinito • Recuerda el local scope • Es perezoso • Demo: https://repl.it/@po5i/PythonMeetupGenerators
  13. Type Annotations • No se realiza chequeo antes de la

    ejecución • Chequeo estático con mypy • Docs: https://docs.python.org/3/library/typing.html • Demo: https://github.com/po5i/python-and-types
  14. • Compose • Pipe • Curry • Fold • Y

    más funciones todavía • Demo Librerías funcionales: toolz