Functional programming? ???? – Ok ok, functions. – Python as a functional programming language?



Functional programming? ???? – Ok ok, functions. – Python as a functional programming language?

0 0


fp-1

Slide meetup del 2017-01-18

On Github PythonMilano / fp-1

Functional Programming in Python 🐍

About me

Riccardo aka @entropiae

Python in the streetsErlang/Elixir (currently) in the sheets

Functional programming? 🤔

(almost) every developer has its own idea about functional programming.

First-class functions Permits to treat functions as data, passed to other functions
Higher-order functions Functions whose accept other functions as arguments, return functions
Recursion instead of iteration

Focus on Tail Call Optimization

(not available in Python 😥)

Immutable data structures
Lazy evaluation
                            len([1, 1/0, '3']) == 3
                        
Emphasis on what is done, not on how is done

Ok ok, functions.

(Mathematical) functions
Pure functions

No side effects

Perfectly pure, almost useless

Practicality beats purity.

Referential transparency

Memoization

No order constraint

Full support for Multi{core, cpu, node} archs

Compiler optimization

Python as a functional programming language?

Python is not, by design, a FP language
However..

..coz everything is an object..

..we have first-class functions! 🎉

1994: higher-order functions were introduced in Python
map: transform a collection
map(lambda x: x + 1, [1, 2, 3]) == [2, 3, 4]
filter: remove elements from a collection
filter(lambda x: x % 2 == 0, [1, 2, 3]) == [2]
reduce: recursively apply an operation on a collection
reduce(lambda x, y: x + y, [1, 2, 3]) == 6

The cornestone of higher-order functions

map() and filter() could be replaced with a list comprehension

There should be one - and preferably only one - obvious way to do it.

GvR doesn't like them 😕

It was proposed to remove them from Python 3
More functions were build on these building blocks

functools, itertools

And now for something completely different
Pietro will show us some code samples ✌️
Functional Programming in Python 🐍