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

Python con un toque funcional

Python con un toque funcional

Compartiremos un poco de nuestra experiencia de Python con este toque especial de la programación funcional y sus diferencias con el enfoque tradicional a través de una serie de ejemplos.

Este lenguaje hoy en día está ganando más popularidad y en este meetup mostraremos el por qué además de cómo alcanzar el Zen en Python.

Quito Lambda

February 27, 2019
Tweet

More Decks by Quito Lambda

Other Decks in Programming

Transcript

  1. Qué es programación funcional? • State-less • Inmutable • Declarativa

    • Sistema de tipos • Funciones de orden superior • Funciones puras
  2. 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)
  3. 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
  4. Funciones de orden superior: map new_list = [] for value

    in values: new_list.append(value * 2) new_list = [x * 2 for x in values]
  5. 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]
  6. 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]
  7. 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)
  8. 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
  9. 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'))
  10. 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
  11. Generators • “yield” keyword • Retorna un iterador / puede

    ser infinito • Recuerda el local scope • Es perezoso • Demo: https://repl.it/@po5i/PythonMeetupGenerators
  12. 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
  13. • Compose • Pipe • Curry • Fold • Y

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