SlideShare a Scribd company logo
Introduction to functional programming in
Python
Francesco Bruni

@brunifrancesco 

Original notebook @ https://github.com/brunifrancesco/cds_talk
Who am I
• MSc Student in Telecommunication Engineering @ Poliba (Italy)

• Despite a Java background, I prefer Python whenever possible

• Data science addicted
What we'll talk about
	 •	 Why functional programming

	 •	 Why Python

	 •	 Functional features in Python

	 ▪	 First class functions

	 ▪	 Immutable vs mutable data

	 ▪	 Lazy evaluation

	 ▪	 Recursion vs loop

	 ▪	 (Manual) Currying

	 ▪	 Monads

	 •	 Useful functional programming resources

	 •	 Conclusions
Why functional programming
	 •	 Think in terms of functions

	 •	 State as function evaluation, not variables assignment

	 •	 Testing is (more) easy

	 •	 A new viewpoint is required
import random

def sum_imperative():

res = 0

for n in [random.random() for _ in range(100)]:

res += n

return res

def sum_functional():

return sum(random.random() for _ in range(100))
Why Python
There are a lot of languages out there..
Pros
	 •	 Mature enough

	 •	 Multiparadigm and multipurpose

	 •	 Easy to learn

	 •	 Interactive shell

	 •	 Multiple implementantions (C, Java, Python, .NET, Ruby, Js)

	 •	 Extending requires few lines of code
Cons
	 •	 Python 3 vs Python 2

	 •	 No typed variables

	 •	 CPython is the widest used implementation

	 •	 Changing implementation/version is not (always) a free iussues transition
Functional features in Python
	 •	 Not all functional patterns apply to Python

	 •	 Hybrid approach is often requested

	 •	 Other libraries needs to be (eventually) integrated
First class functions
	 •	 Functions are objects too

	 •	 They have fields too and some basic methods
def func_1(x="32"):

assert(x)

def func_2():

return "wow!"

func_3 = lambda some_param: str(some_param)
High order functions
	 •	 Functions which accept functions as params;

	 •	 Functions which return other functions;

	 •	 Python std lib examples for mapping: filter, map, sorted,

	 •	 Python std lib examples for reducing: max, min, sum

Task: given the previous generated list, filter some number out and sort the result by the
second digit.
def filter_out():



result = python_better_approach()



exclude = map(lambda item: item ** 2, range(30))

result = filter(lambda item: item not in exclude, result)



return sorted(result, key=lambda item: str(item)[1])



filter(lambda item: item not in map(lambda item: item ** 2, range(30)),
python_better_approach(size=100))
Class for function composition
Handle class creation via a new class syntax, allowing a "static" configuration
from collections.abc import Callable

class ExcludeFunction(Callable):

def __init__(self, exclude_function):

self.exclude_function= exclude_function



def __call__(self, value):

return None if not value else self.exclude_function(value)

result = python_better_approach(size=100)

exclude_function_1 = lambda item: item ** 2

ex_func = ExcludeFunction(exclude_function_1)

result = filter(lambda item: not item == ex_func(item), result)

assert(sorted(result, key=lambda item: str(item)[1]) == filter_out())
Immutable vs mutable data structure
	 •	 Since state is not given by variable assignement, there's no need of mutables data

	 •	 (Almost) no classes are required

	 •	 Instead of lists, tuples are reccomanded

	 •	 Instead of classes, namedtuple can be used
from collections.abc import Callable

class ExcludeFunction(Callable):

def __init__(self, exclude_function):

self.exclude_function= exclude_function



def __call__(self, value):

return None if not value else self.exclude_function(value)

result = python_better_approach(size=100)

exclude_function_1 = lambda item: item ** 2

ex_func = ExcludeFunction(exclude_function_1)

result = filter(lambda item: not item == ex_func(item), result)

assert(sorted(result, key=lambda item: str(item)[1]) == filter_out())
Strict vs not strict evaluation
	 •	 Strict evaluation requires that all operators needs to be evaluated

	 •	 Non strict (or lazy) evaluation, evaluates expression if and when requested
Use case: Python iterables structures
• Iterable: objects than can be iterated;

• Iterator: objects than can be iterated and consumed only once, with two main problems:

	 ▪	 They track their state in a stateful object

	 ▪	 Their values are generated a priori

	 ▪	 They aren't lazy

• Generators: lazy evaluated data structures:

	 ▪	 They track state in function, instead of object

	 ▪	 They don't act as normal functions

	 ▪	 They generate next member when invoked
def _iter(size=100):

return iter(python_better_approach(size=size))

def lazy_python_approach(size=100):

for item in range(10, size):

if not item % 2 and not str(item).endswith("4"):

yield item

def lazy_new_python_approach(size=100):

yield from (r for r in range(10, size) if not r % 2 and not str(r).endswith("4"))
Recursion vs loop
	 •	 Functional programming requires a recursion approach vs loop iteration

	 •	 Python suffers by recursion limit

	 •	 Python does not offer any tail call optimization
def fact_loop(n):

if n == 0: return 1

f= 1

for i in range(2,n):

f *= i

return f

def fact(n):

if n == 0: return 1

else: return n*fact(n-1)
Currying
Multiple arguments functions mapped to single arguments functions
from random import randrange

def mult(a, b, c ):

def wrapper_1(b):

def wrapper_2(c):

return a*b*c

return wrapper_2(c)

return wrapper_1(b)

def mult_2(a):

def wrapper_1(b):

def wrapper_2(c):

return a*b*c

return wrapper_2

return wrapper_1
Partials
Python provides "partial" functions for manual currying
from functools import reduce

import operator

import random

def two_random_sum():

return reduce(operator.sum, [random.random()]*2)

def three_random_product():

return reduce(operator.mul, [random.random()]*3)

def four_random_sub():

return reduce(operator.sub, [random.random()]*4)

def five_random_pow ():

return reduce(operator.pow, [random.random()]*5)
def handle_random_numbers(size, function):

return reduce(function, [random.random()]*size)

two_random_sum = partial(handle_random_numbers, size=2)

three_random_sum = partial(handle_random_numbers, size=3)

two_random_pow = partial(handle_random_numbers, size=2, function=operator.pow)

five_random_product = partial(handle_random_numbers, size=5, function=operator.mul)
Decorator Pattern
Return a modified version of a decorated function
from functools import wraps

from functools import partial

def get_ned_data(n):

def get_doubled_data(func, *args, **kwargs):

@wraps(func)

def _inner(*args, **kwargs):

kwargs["new_param"] = kwargs["some_param"]*n

return func(*args, **kwargs)

return _inner

return get_doubled_data
@get_ned_data(n=2)

def double_func(*args, **kwargs):

assert(kwargs["new_param"] == kwargs["some_param"]*2)

@get_ned_data(n=3)

def triple_func(*args, **kwargs):

assert(kwargs["new_param"] == kwargs["some_param"]*3)



double_func(some_param=3)

triple_func(some_param=5)
Monads
	 •	 How to handle errors in functional programming?

	 •	 Practical example: parsing and transforming data coming from HTTP request

	 •	 Python "std" libs have no support
from fn.monad import optionable

def get(request, *args, **kwargs):

@optionable

def _get_values(data):

return data.get("values", None)

_split = lambda item: item.split(",")

_strip = lambda item: item.replace(" ", "")

_filter = lambda item: list(filter(lambda i: i, item))

values = _get_values(request.GET).map(_strip).map(_split).map(_filter).get_or(["v1,v2"])

return values
from collections import namedtuple

def test():

_req_class = namedtuple("Request", ("GET"))



request_1 = _req_class(dict(values="v1, v2,v3"))

request_2 = _req_class(dict(values="v1,v2,v3 "))

request_3 = _req_class(dict(values="v1, v2,v3, "))



assert(get(request_1) == ['v1', 'v2', 'v3'])

assert(get(request_2) == ['v1', 'v2', 'v3'])

assert(get(request_3) == ['v1', 'v2', 'v3'])
@get_object(MeterInstance)

def post(self, request, *args, **kwargs):

@optionable

def get_data(data):

return data.get("data", None)

return get_data(request.DATA)

.map(

lambda item:

handle_error_configuration(item, kwargs["contatore"]))

.map(

lambda item:

Response(dict(detail=item), status=200))

.get_or(Response("BadRequest", status=400))
Useful libraries
• Fn.py (https://github.com/kachayev/fn.py) (A bit of Scala, ported to Python)

• Underscore.py (ported from underscore_js)
Summary
	 •	 Functional programming for writing more succint code

	 •	 Change viewpoint: think in terms of functions

	 •	 Python seems for dummies until you show some cool features

	 •	 Python can be slow but with a fine tuning can be more efficient
Questions?

More Related Content

What's hot

Ruby Programming Assignment Help
Ruby Programming Assignment HelpRuby Programming Assignment Help
Ruby Programming Assignment Help
HelpWithAssignment.com
 
Functional Programming Patterns (BuildStuff '14)
Functional Programming Patterns (BuildStuff '14)Functional Programming Patterns (BuildStuff '14)
Functional Programming Patterns (BuildStuff '14)
Scott Wlaschin
 
Learning Functional Programming Without Growing a Neckbeard
Learning Functional Programming Without Growing a NeckbeardLearning Functional Programming Without Growing a Neckbeard
Learning Functional Programming Without Growing a Neckbeard
Kelsey Gilmore-Innis
 
Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)
Jonas Bonér
 
Python in 90 minutes
Python in 90 minutesPython in 90 minutes
Python in 90 minutes
Bardia Heydari
 
Lecture02 class -_templatev2
Lecture02 class -_templatev2Lecture02 class -_templatev2
Lecture02 class -_templatev2
Hariz Mustafa
 
Functional programming ii
Functional programming iiFunctional programming ii
Functional programming ii
Prashant Kalkar
 
Why we cannot ignore Functional Programming
Why we cannot ignore Functional ProgrammingWhy we cannot ignore Functional Programming
Why we cannot ignore Functional Programming
Mario Fusco
 
Functional programming
Functional programmingFunctional programming
Functional programming
Prashant Kalkar
 
Memory Management C++ (Peeling operator new() and delete())
Memory Management C++ (Peeling operator new() and delete())Memory Management C++ (Peeling operator new() and delete())
Memory Management C++ (Peeling operator new() and delete())
Sameer Rathoud
 
Twins: Object Oriented Programming and Functional Programming
Twins: Object Oriented Programming and Functional ProgrammingTwins: Object Oriented Programming and Functional Programming
Twins: Object Oriented Programming and Functional Programming
RichardWarburton
 
Python Closures Explained | What are Closures in Python | Python Closures
Python Closures Explained | What are Closures in Python | Python ClosuresPython Closures Explained | What are Closures in Python | Python Closures
Python Closures Explained | What are Closures in Python | Python Closures
Intellipaat
 
Iterarators and generators in python
Iterarators and generators in pythonIterarators and generators in python
Iterarators and generators in python
Sarfaraz Ghanta
 
Scala ntnu
Scala ntnuScala ntnu
Scala collections api expressivity and brevity upgrade from java
Scala collections api  expressivity and brevity upgrade from javaScala collections api  expressivity and brevity upgrade from java
Scala collections api expressivity and brevity upgrade from java
IndicThreads
 
Scala - core features
Scala - core featuresScala - core features
Scala - core features
Łukasz Wójcik
 
Scala for curious
Scala for curiousScala for curious
Scala for curious
Tim (dev-tim) Zadorozhniy
 
julia-Latest Programming language
julia-Latest Programming  languagejulia-Latest Programming  language
julia-Latest Programming language
Nithya Prakasan
 
Clojure, Plain and Simple
Clojure, Plain and SimpleClojure, Plain and Simple
Clojure, Plain and Simple
Ben Mabey
 
Operator overload rr
Operator overload  rrOperator overload  rr
Operator overload rr
Dhivya Shanmugam
 

What's hot (20)

Ruby Programming Assignment Help
Ruby Programming Assignment HelpRuby Programming Assignment Help
Ruby Programming Assignment Help
 
Functional Programming Patterns (BuildStuff '14)
Functional Programming Patterns (BuildStuff '14)Functional Programming Patterns (BuildStuff '14)
Functional Programming Patterns (BuildStuff '14)
 
Learning Functional Programming Without Growing a Neckbeard
Learning Functional Programming Without Growing a NeckbeardLearning Functional Programming Without Growing a Neckbeard
Learning Functional Programming Without Growing a Neckbeard
 
Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)
 
Python in 90 minutes
Python in 90 minutesPython in 90 minutes
Python in 90 minutes
 
Lecture02 class -_templatev2
Lecture02 class -_templatev2Lecture02 class -_templatev2
Lecture02 class -_templatev2
 
Functional programming ii
Functional programming iiFunctional programming ii
Functional programming ii
 
Why we cannot ignore Functional Programming
Why we cannot ignore Functional ProgrammingWhy we cannot ignore Functional Programming
Why we cannot ignore Functional Programming
 
Functional programming
Functional programmingFunctional programming
Functional programming
 
Memory Management C++ (Peeling operator new() and delete())
Memory Management C++ (Peeling operator new() and delete())Memory Management C++ (Peeling operator new() and delete())
Memory Management C++ (Peeling operator new() and delete())
 
Twins: Object Oriented Programming and Functional Programming
Twins: Object Oriented Programming and Functional ProgrammingTwins: Object Oriented Programming and Functional Programming
Twins: Object Oriented Programming and Functional Programming
 
Python Closures Explained | What are Closures in Python | Python Closures
Python Closures Explained | What are Closures in Python | Python ClosuresPython Closures Explained | What are Closures in Python | Python Closures
Python Closures Explained | What are Closures in Python | Python Closures
 
Iterarators and generators in python
Iterarators and generators in pythonIterarators and generators in python
Iterarators and generators in python
 
Scala ntnu
Scala ntnuScala ntnu
Scala ntnu
 
Scala collections api expressivity and brevity upgrade from java
Scala collections api  expressivity and brevity upgrade from javaScala collections api  expressivity and brevity upgrade from java
Scala collections api expressivity and brevity upgrade from java
 
Scala - core features
Scala - core featuresScala - core features
Scala - core features
 
Scala for curious
Scala for curiousScala for curious
Scala for curious
 
julia-Latest Programming language
julia-Latest Programming  languagejulia-Latest Programming  language
julia-Latest Programming language
 
Clojure, Plain and Simple
Clojure, Plain and SimpleClojure, Plain and Simple
Clojure, Plain and Simple
 
Operator overload rr
Operator overload  rrOperator overload  rr
Operator overload rr
 

Viewers also liked

Club degli sviluppatori: Sencha Touch - 1°parte
Club degli sviluppatori: Sencha Touch - 1°parteClub degli sviluppatori: Sencha Touch - 1°parte
Club degli sviluppatori: Sencha Touch - 1°parte
Giuseppe Toto
 
ANTLR - crea il tuo souce-to-source compiler
ANTLR - crea il tuo souce-to-source compilerANTLR - crea il tuo souce-to-source compiler
ANTLR - crea il tuo souce-to-source compiler
Giuseppe Santoro
 
Containing the world with Docker
Containing the world with DockerContaining the world with Docker
Containing the world with Docker
Giuseppe Piccolo
 
Club degli sviluppatori : performance optimization - 2° Parte
Club degli sviluppatori : performance optimization - 2° ParteClub degli sviluppatori : performance optimization - 2° Parte
Club degli sviluppatori : performance optimization - 2° Parte
Giuseppe Toto
 
Sencha touch: Sviluppare un'app - 4° parte
Sencha touch: Sviluppare un'app - 4° parteSencha touch: Sviluppare un'app - 4° parte
Sencha touch: Sviluppare un'app - 4° parte
Giuseppe Toto
 
Open street map
Open street mapOpen street map
Open street map
Michelantonio Trizio
 
Sencha touch: panoramica e orientamento sul codice
Sencha touch: panoramica e orientamento sul codiceSencha touch: panoramica e orientamento sul codice
Sencha touch: panoramica e orientamento sul codice
Giuseppe Toto
 
Customer centric agile @ ACE! conference
Customer centric agile @ ACE! conferenceCustomer centric agile @ ACE! conference
Customer centric agile @ ACE! conference
Angel Diaz-Maroto
 
Alberto di Cagno_L'opensource nella cultura giuridica italiana
Alberto di Cagno_L'opensource nella cultura giuridica italianaAlberto di Cagno_L'opensource nella cultura giuridica italiana
Alberto di Cagno_L'opensource nella cultura giuridica italiana
La Scuola Open Source
 
Rethink programming: a functional approach
Rethink programming: a functional approachRethink programming: a functional approach
Rethink programming: a functional approach
Francesco Bruni
 
Basic NLP with Python and NLTK
Basic NLP with Python and NLTKBasic NLP with Python and NLTK
Basic NLP with Python and NLTK
Francesco Bruni
 
Continuous Integration/Deployment with Docker and Jenkins
Continuous Integration/Deployment with Docker and JenkinsContinuous Integration/Deployment with Docker and Jenkins
Continuous Integration/Deployment with Docker and Jenkins
Francesco Bruni
 
NoSQL databases pros and cons
NoSQL databases pros and consNoSQL databases pros and cons
NoSQL databases pros and cons
Fabio Fumarola
 
Metricas Ingenieria De Software
Metricas Ingenieria De SoftwareMetricas Ingenieria De Software
Metricas Ingenieria De Software
Ricardo
 
How to deploy a Java application on Google App engine Flexible environment
How to deploy a Java application on Google App engine Flexible environmentHow to deploy a Java application on Google App engine Flexible environment
How to deploy a Java application on Google App engine Flexible environment
Michelantonio Trizio
 
SlideShare 101
SlideShare 101SlideShare 101
SlideShare 101
Amit Ranjan
 

Viewers also liked (16)

Club degli sviluppatori: Sencha Touch - 1°parte
Club degli sviluppatori: Sencha Touch - 1°parteClub degli sviluppatori: Sencha Touch - 1°parte
Club degli sviluppatori: Sencha Touch - 1°parte
 
ANTLR - crea il tuo souce-to-source compiler
ANTLR - crea il tuo souce-to-source compilerANTLR - crea il tuo souce-to-source compiler
ANTLR - crea il tuo souce-to-source compiler
 
Containing the world with Docker
Containing the world with DockerContaining the world with Docker
Containing the world with Docker
 
Club degli sviluppatori : performance optimization - 2° Parte
Club degli sviluppatori : performance optimization - 2° ParteClub degli sviluppatori : performance optimization - 2° Parte
Club degli sviluppatori : performance optimization - 2° Parte
 
Sencha touch: Sviluppare un'app - 4° parte
Sencha touch: Sviluppare un'app - 4° parteSencha touch: Sviluppare un'app - 4° parte
Sencha touch: Sviluppare un'app - 4° parte
 
Open street map
Open street mapOpen street map
Open street map
 
Sencha touch: panoramica e orientamento sul codice
Sencha touch: panoramica e orientamento sul codiceSencha touch: panoramica e orientamento sul codice
Sencha touch: panoramica e orientamento sul codice
 
Customer centric agile @ ACE! conference
Customer centric agile @ ACE! conferenceCustomer centric agile @ ACE! conference
Customer centric agile @ ACE! conference
 
Alberto di Cagno_L'opensource nella cultura giuridica italiana
Alberto di Cagno_L'opensource nella cultura giuridica italianaAlberto di Cagno_L'opensource nella cultura giuridica italiana
Alberto di Cagno_L'opensource nella cultura giuridica italiana
 
Rethink programming: a functional approach
Rethink programming: a functional approachRethink programming: a functional approach
Rethink programming: a functional approach
 
Basic NLP with Python and NLTK
Basic NLP with Python and NLTKBasic NLP with Python and NLTK
Basic NLP with Python and NLTK
 
Continuous Integration/Deployment with Docker and Jenkins
Continuous Integration/Deployment with Docker and JenkinsContinuous Integration/Deployment with Docker and Jenkins
Continuous Integration/Deployment with Docker and Jenkins
 
NoSQL databases pros and cons
NoSQL databases pros and consNoSQL databases pros and cons
NoSQL databases pros and cons
 
Metricas Ingenieria De Software
Metricas Ingenieria De SoftwareMetricas Ingenieria De Software
Metricas Ingenieria De Software
 
How to deploy a Java application on Google App engine Flexible environment
How to deploy a Java application on Google App engine Flexible environmentHow to deploy a Java application on Google App engine Flexible environment
How to deploy a Java application on Google App engine Flexible environment
 
SlideShare 101
SlideShare 101SlideShare 101
SlideShare 101
 

Similar to Introduction to Functional Programming

Slide PF Pertemuan 2.pptx
Slide PF Pertemuan 2.pptxSlide PF Pertemuan 2.pptx
Slide PF Pertemuan 2.pptx
LucidAxel
 
Thinking in Functions: Functional Programming in Python
Thinking in Functions: Functional Programming in PythonThinking in Functions: Functional Programming in Python
Thinking in Functions: Functional Programming in Python
Anoop Thomas Mathew
 
Functions2.pptx
Functions2.pptxFunctions2.pptx
Functions2.pptx
AkhilTyagi42
 
Functional programming in python
Functional programming in pythonFunctional programming in python
Functional programming in python
Edward D. Weinberger
 
Functional programming in python
Functional programming in pythonFunctional programming in python
Functional programming in python
Edward D. Weinberger
 
Functions.pdf
Functions.pdfFunctions.pdf
Functions.pdf
kailashGusain3
 
Functionscs12 ppt.pdf
Functionscs12 ppt.pdfFunctionscs12 ppt.pdf
Functionscs12 ppt.pdf
RiteshKumarPradhan1
 
10. haskell Modules
10. haskell Modules10. haskell Modules
10. haskell Modules
Sebastian Rettig
 
Functions_21_22.pdf
Functions_21_22.pdfFunctions_21_22.pdf
Functions_21_22.pdf
paijitk
 
Python_Functions_Unit1.pptx
Python_Functions_Unit1.pptxPython_Functions_Unit1.pptx
Python_Functions_Unit1.pptx
Koteswari Kasireddy
 
Functions2.pdf
Functions2.pdfFunctions2.pdf
Functions2.pdf
Daddy84
 
Programming with Python - Week 3
Programming with Python - Week 3Programming with Python - Week 3
Programming with Python - Week 3
Ahmet Bulut
 
Functional Programming in Swift
Functional Programming in SwiftFunctional Programming in Swift
Functional Programming in Swift
Saugat Gautam
 
cbse class 12 Python Functions2 for class 12 .pptx
cbse class 12 Python Functions2 for class 12 .pptxcbse class 12 Python Functions2 for class 12 .pptx
cbse class 12 Python Functions2 for class 12 .pptx
tcsonline1222
 
Functional Programming
Functional ProgrammingFunctional Programming
Functional Programming
Olexandra Dmytrenko
 
PYTHON -Chapter 2 - Functions, Exception, Modules and Files -MAULIK BOR...
PYTHON -Chapter 2 - Functions,   Exception, Modules  and    Files -MAULIK BOR...PYTHON -Chapter 2 - Functions,   Exception, Modules  and    Files -MAULIK BOR...
PYTHON -Chapter 2 - Functions, Exception, Modules and Files -MAULIK BOR...
Maulik Borsaniya
 
Functional python
Functional pythonFunctional python
Functional python
Jesué Junior
 
Funkcija, objekt, python
Funkcija, objekt, pythonFunkcija, objekt, python
Funkcija, objekt, python
Robert Lujo
 
Bartosz Milewski, “Re-discovering Monads in C++”
Bartosz Milewski, “Re-discovering Monads in C++”Bartosz Milewski, “Re-discovering Monads in C++”
Bartosz Milewski, “Re-discovering Monads in C++”
Platonov Sergey
 
Functions2.pdf
Functions2.pdfFunctions2.pdf
Functions2.pdf
prasnt1
 

Similar to Introduction to Functional Programming (20)

Slide PF Pertemuan 2.pptx
Slide PF Pertemuan 2.pptxSlide PF Pertemuan 2.pptx
Slide PF Pertemuan 2.pptx
 
Thinking in Functions: Functional Programming in Python
Thinking in Functions: Functional Programming in PythonThinking in Functions: Functional Programming in Python
Thinking in Functions: Functional Programming in Python
 
Functions2.pptx
Functions2.pptxFunctions2.pptx
Functions2.pptx
 
Functional programming in python
Functional programming in pythonFunctional programming in python
Functional programming in python
 
Functional programming in python
Functional programming in pythonFunctional programming in python
Functional programming in python
 
Functions.pdf
Functions.pdfFunctions.pdf
Functions.pdf
 
Functionscs12 ppt.pdf
Functionscs12 ppt.pdfFunctionscs12 ppt.pdf
Functionscs12 ppt.pdf
 
10. haskell Modules
10. haskell Modules10. haskell Modules
10. haskell Modules
 
Functions_21_22.pdf
Functions_21_22.pdfFunctions_21_22.pdf
Functions_21_22.pdf
 
Python_Functions_Unit1.pptx
Python_Functions_Unit1.pptxPython_Functions_Unit1.pptx
Python_Functions_Unit1.pptx
 
Functions2.pdf
Functions2.pdfFunctions2.pdf
Functions2.pdf
 
Programming with Python - Week 3
Programming with Python - Week 3Programming with Python - Week 3
Programming with Python - Week 3
 
Functional Programming in Swift
Functional Programming in SwiftFunctional Programming in Swift
Functional Programming in Swift
 
cbse class 12 Python Functions2 for class 12 .pptx
cbse class 12 Python Functions2 for class 12 .pptxcbse class 12 Python Functions2 for class 12 .pptx
cbse class 12 Python Functions2 for class 12 .pptx
 
Functional Programming
Functional ProgrammingFunctional Programming
Functional Programming
 
PYTHON -Chapter 2 - Functions, Exception, Modules and Files -MAULIK BOR...
PYTHON -Chapter 2 - Functions,   Exception, Modules  and    Files -MAULIK BOR...PYTHON -Chapter 2 - Functions,   Exception, Modules  and    Files -MAULIK BOR...
PYTHON -Chapter 2 - Functions, Exception, Modules and Files -MAULIK BOR...
 
Functional python
Functional pythonFunctional python
Functional python
 
Funkcija, objekt, python
Funkcija, objekt, pythonFunkcija, objekt, python
Funkcija, objekt, python
 
Bartosz Milewski, “Re-discovering Monads in C++”
Bartosz Milewski, “Re-discovering Monads in C++”Bartosz Milewski, “Re-discovering Monads in C++”
Bartosz Milewski, “Re-discovering Monads in C++”
 
Functions2.pdf
Functions2.pdfFunctions2.pdf
Functions2.pdf
 

Recently uploaded

How Can Hiring A Mobile App Development Company Help Your Business Grow?
How Can Hiring A Mobile App Development Company Help Your Business Grow?How Can Hiring A Mobile App Development Company Help Your Business Grow?
How Can Hiring A Mobile App Development Company Help Your Business Grow?
ToXSL Technologies
 
Enums On Steroids - let's look at sealed classes !
Enums On Steroids - let's look at sealed classes !Enums On Steroids - let's look at sealed classes !
Enums On Steroids - let's look at sealed classes !
Marcin Chrost
 
ACE - Team 24 Wrapup event at ahmedabad.
ACE - Team 24 Wrapup event at ahmedabad.ACE - Team 24 Wrapup event at ahmedabad.
ACE - Team 24 Wrapup event at ahmedabad.
Maitrey Patel
 
A Comprehensive Guide on Implementing Real-World Mobile Testing Strategies fo...
A Comprehensive Guide on Implementing Real-World Mobile Testing Strategies fo...A Comprehensive Guide on Implementing Real-World Mobile Testing Strategies fo...
A Comprehensive Guide on Implementing Real-World Mobile Testing Strategies fo...
kalichargn70th171
 
一比一原版(USF毕业证)旧金山大学毕业证如何办理
一比一原版(USF毕业证)旧金山大学毕业证如何办理一比一原版(USF毕业证)旧金山大学毕业证如何办理
一比一原版(USF毕业证)旧金山大学毕业证如何办理
dakas1
 
Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...
Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...
Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...
Paul Brebner
 
The Rising Future of CPaaS in the Middle East 2024
The Rising Future of CPaaS in the Middle East 2024The Rising Future of CPaaS in the Middle East 2024
The Rising Future of CPaaS in the Middle East 2024
Yara Milbes
 
DECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSIS
DECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSISDECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSIS
DECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSIS
Tier1 app
 
Project Management: The Role of Project Dashboards.pdf
Project Management: The Role of Project Dashboards.pdfProject Management: The Role of Project Dashboards.pdf
Project Management: The Role of Project Dashboards.pdf
Karya Keeper
 
Unveiling the Advantages of Agile Software Development.pdf
Unveiling the Advantages of Agile Software Development.pdfUnveiling the Advantages of Agile Software Development.pdf
Unveiling the Advantages of Agile Software Development.pdf
brainerhub1
 
UI5con 2024 - Keynote: Latest News about UI5 and it’s Ecosystem
UI5con 2024 - Keynote: Latest News about UI5 and it’s EcosystemUI5con 2024 - Keynote: Latest News about UI5 and it’s Ecosystem
UI5con 2024 - Keynote: Latest News about UI5 and it’s Ecosystem
Peter Muessig
 
ppt on the brain chip neuralink.pptx
ppt  on   the brain  chip neuralink.pptxppt  on   the brain  chip neuralink.pptx
ppt on the brain chip neuralink.pptx
Reetu63
 
一比一原版(sdsu毕业证书)圣地亚哥州立大学毕业证如何办理
一比一原版(sdsu毕业证书)圣地亚哥州立大学毕业证如何办理一比一原版(sdsu毕业证书)圣地亚哥州立大学毕业证如何办理
一比一原版(sdsu毕业证书)圣地亚哥州立大学毕业证如何办理
kgyxske
 
Baha Majid WCA4Z IBM Z Customer Council Boston June 2024.pdf
Baha Majid WCA4Z IBM Z Customer Council Boston June 2024.pdfBaha Majid WCA4Z IBM Z Customer Council Boston June 2024.pdf
Baha Majid WCA4Z IBM Z Customer Council Boston June 2024.pdf
Baha Majid
 
Using Query Store in Azure PostgreSQL to Understand Query Performance
Using Query Store in Azure PostgreSQL to Understand Query PerformanceUsing Query Store in Azure PostgreSQL to Understand Query Performance
Using Query Store in Azure PostgreSQL to Understand Query Performance
Grant Fritchey
 
一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理
一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理
一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理
dakas1
 
GreenCode-A-VSCode-Plugin--Dario-Jurisic
GreenCode-A-VSCode-Plugin--Dario-JurisicGreenCode-A-VSCode-Plugin--Dario-Jurisic
GreenCode-A-VSCode-Plugin--Dario-Jurisic
Green Software Development
 
Oracle 23c New Features For DBAs and Developers.pptx
Oracle 23c New Features For DBAs and Developers.pptxOracle 23c New Features For DBAs and Developers.pptx
Oracle 23c New Features For DBAs and Developers.pptx
Remote DBA Services
 
Oracle Database 19c New Features for DBAs and Developers.pptx
Oracle Database 19c New Features for DBAs and Developers.pptxOracle Database 19c New Features for DBAs and Developers.pptx
Oracle Database 19c New Features for DBAs and Developers.pptx
Remote DBA Services
 
Mobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona InfotechMobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona Infotech
Drona Infotech
 

Recently uploaded (20)

How Can Hiring A Mobile App Development Company Help Your Business Grow?
How Can Hiring A Mobile App Development Company Help Your Business Grow?How Can Hiring A Mobile App Development Company Help Your Business Grow?
How Can Hiring A Mobile App Development Company Help Your Business Grow?
 
Enums On Steroids - let's look at sealed classes !
Enums On Steroids - let's look at sealed classes !Enums On Steroids - let's look at sealed classes !
Enums On Steroids - let's look at sealed classes !
 
ACE - Team 24 Wrapup event at ahmedabad.
ACE - Team 24 Wrapup event at ahmedabad.ACE - Team 24 Wrapup event at ahmedabad.
ACE - Team 24 Wrapup event at ahmedabad.
 
A Comprehensive Guide on Implementing Real-World Mobile Testing Strategies fo...
A Comprehensive Guide on Implementing Real-World Mobile Testing Strategies fo...A Comprehensive Guide on Implementing Real-World Mobile Testing Strategies fo...
A Comprehensive Guide on Implementing Real-World Mobile Testing Strategies fo...
 
一比一原版(USF毕业证)旧金山大学毕业证如何办理
一比一原版(USF毕业证)旧金山大学毕业证如何办理一比一原版(USF毕业证)旧金山大学毕业证如何办理
一比一原版(USF毕业证)旧金山大学毕业证如何办理
 
Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...
Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...
Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...
 
The Rising Future of CPaaS in the Middle East 2024
The Rising Future of CPaaS in the Middle East 2024The Rising Future of CPaaS in the Middle East 2024
The Rising Future of CPaaS in the Middle East 2024
 
DECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSIS
DECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSISDECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSIS
DECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSIS
 
Project Management: The Role of Project Dashboards.pdf
Project Management: The Role of Project Dashboards.pdfProject Management: The Role of Project Dashboards.pdf
Project Management: The Role of Project Dashboards.pdf
 
Unveiling the Advantages of Agile Software Development.pdf
Unveiling the Advantages of Agile Software Development.pdfUnveiling the Advantages of Agile Software Development.pdf
Unveiling the Advantages of Agile Software Development.pdf
 
UI5con 2024 - Keynote: Latest News about UI5 and it’s Ecosystem
UI5con 2024 - Keynote: Latest News about UI5 and it’s EcosystemUI5con 2024 - Keynote: Latest News about UI5 and it’s Ecosystem
UI5con 2024 - Keynote: Latest News about UI5 and it’s Ecosystem
 
ppt on the brain chip neuralink.pptx
ppt  on   the brain  chip neuralink.pptxppt  on   the brain  chip neuralink.pptx
ppt on the brain chip neuralink.pptx
 
一比一原版(sdsu毕业证书)圣地亚哥州立大学毕业证如何办理
一比一原版(sdsu毕业证书)圣地亚哥州立大学毕业证如何办理一比一原版(sdsu毕业证书)圣地亚哥州立大学毕业证如何办理
一比一原版(sdsu毕业证书)圣地亚哥州立大学毕业证如何办理
 
Baha Majid WCA4Z IBM Z Customer Council Boston June 2024.pdf
Baha Majid WCA4Z IBM Z Customer Council Boston June 2024.pdfBaha Majid WCA4Z IBM Z Customer Council Boston June 2024.pdf
Baha Majid WCA4Z IBM Z Customer Council Boston June 2024.pdf
 
Using Query Store in Azure PostgreSQL to Understand Query Performance
Using Query Store in Azure PostgreSQL to Understand Query PerformanceUsing Query Store in Azure PostgreSQL to Understand Query Performance
Using Query Store in Azure PostgreSQL to Understand Query Performance
 
一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理
一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理
一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理
 
GreenCode-A-VSCode-Plugin--Dario-Jurisic
GreenCode-A-VSCode-Plugin--Dario-JurisicGreenCode-A-VSCode-Plugin--Dario-Jurisic
GreenCode-A-VSCode-Plugin--Dario-Jurisic
 
Oracle 23c New Features For DBAs and Developers.pptx
Oracle 23c New Features For DBAs and Developers.pptxOracle 23c New Features For DBAs and Developers.pptx
Oracle 23c New Features For DBAs and Developers.pptx
 
Oracle Database 19c New Features for DBAs and Developers.pptx
Oracle Database 19c New Features for DBAs and Developers.pptxOracle Database 19c New Features for DBAs and Developers.pptx
Oracle Database 19c New Features for DBAs and Developers.pptx
 
Mobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona InfotechMobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona Infotech
 

Introduction to Functional Programming

  • 1. Introduction to functional programming in Python Francesco Bruni @brunifrancesco Original notebook @ https://github.com/brunifrancesco/cds_talk
  • 2. Who am I • MSc Student in Telecommunication Engineering @ Poliba (Italy) • Despite a Java background, I prefer Python whenever possible • Data science addicted
  • 3. What we'll talk about • Why functional programming • Why Python • Functional features in Python ▪ First class functions ▪ Immutable vs mutable data ▪ Lazy evaluation ▪ Recursion vs loop ▪ (Manual) Currying ▪ Monads • Useful functional programming resources • Conclusions
  • 4. Why functional programming • Think in terms of functions • State as function evaluation, not variables assignment • Testing is (more) easy • A new viewpoint is required
  • 5. import random def sum_imperative(): res = 0 for n in [random.random() for _ in range(100)]: res += n return res def sum_functional(): return sum(random.random() for _ in range(100))
  • 6. Why Python There are a lot of languages out there..
  • 7. Pros • Mature enough • Multiparadigm and multipurpose • Easy to learn • Interactive shell • Multiple implementantions (C, Java, Python, .NET, Ruby, Js) • Extending requires few lines of code
  • 8. Cons • Python 3 vs Python 2 • No typed variables • CPython is the widest used implementation • Changing implementation/version is not (always) a free iussues transition
  • 9. Functional features in Python • Not all functional patterns apply to Python • Hybrid approach is often requested • Other libraries needs to be (eventually) integrated
  • 10. First class functions • Functions are objects too • They have fields too and some basic methods
  • 11. def func_1(x="32"): assert(x) def func_2(): return "wow!" func_3 = lambda some_param: str(some_param)
  • 12. High order functions • Functions which accept functions as params; • Functions which return other functions; • Python std lib examples for mapping: filter, map, sorted, • Python std lib examples for reducing: max, min, sum Task: given the previous generated list, filter some number out and sort the result by the second digit.
  • 13. def filter_out(): result = python_better_approach() exclude = map(lambda item: item ** 2, range(30)) result = filter(lambda item: item not in exclude, result) return sorted(result, key=lambda item: str(item)[1]) filter(lambda item: item not in map(lambda item: item ** 2, range(30)), python_better_approach(size=100))
  • 14. Class for function composition Handle class creation via a new class syntax, allowing a "static" configuration
  • 15. from collections.abc import Callable class ExcludeFunction(Callable): def __init__(self, exclude_function): self.exclude_function= exclude_function def __call__(self, value): return None if not value else self.exclude_function(value) result = python_better_approach(size=100) exclude_function_1 = lambda item: item ** 2 ex_func = ExcludeFunction(exclude_function_1) result = filter(lambda item: not item == ex_func(item), result) assert(sorted(result, key=lambda item: str(item)[1]) == filter_out())
  • 16. Immutable vs mutable data structure • Since state is not given by variable assignement, there's no need of mutables data • (Almost) no classes are required • Instead of lists, tuples are reccomanded • Instead of classes, namedtuple can be used
  • 17. from collections.abc import Callable class ExcludeFunction(Callable): def __init__(self, exclude_function): self.exclude_function= exclude_function def __call__(self, value): return None if not value else self.exclude_function(value) result = python_better_approach(size=100) exclude_function_1 = lambda item: item ** 2 ex_func = ExcludeFunction(exclude_function_1) result = filter(lambda item: not item == ex_func(item), result) assert(sorted(result, key=lambda item: str(item)[1]) == filter_out())
  • 18. Strict vs not strict evaluation • Strict evaluation requires that all operators needs to be evaluated • Non strict (or lazy) evaluation, evaluates expression if and when requested
  • 19. Use case: Python iterables structures • Iterable: objects than can be iterated; • Iterator: objects than can be iterated and consumed only once, with two main problems: ▪ They track their state in a stateful object ▪ Their values are generated a priori ▪ They aren't lazy • Generators: lazy evaluated data structures: ▪ They track state in function, instead of object ▪ They don't act as normal functions ▪ They generate next member when invoked
  • 20. def _iter(size=100): return iter(python_better_approach(size=size)) def lazy_python_approach(size=100): for item in range(10, size): if not item % 2 and not str(item).endswith("4"): yield item def lazy_new_python_approach(size=100): yield from (r for r in range(10, size) if not r % 2 and not str(r).endswith("4"))
  • 21. Recursion vs loop • Functional programming requires a recursion approach vs loop iteration • Python suffers by recursion limit • Python does not offer any tail call optimization
  • 22. def fact_loop(n): if n == 0: return 1 f= 1 for i in range(2,n): f *= i return f def fact(n): if n == 0: return 1 else: return n*fact(n-1)
  • 23. Currying Multiple arguments functions mapped to single arguments functions
  • 24. from random import randrange def mult(a, b, c ): def wrapper_1(b): def wrapper_2(c): return a*b*c return wrapper_2(c) return wrapper_1(b) def mult_2(a): def wrapper_1(b): def wrapper_2(c): return a*b*c return wrapper_2 return wrapper_1
  • 25. Partials Python provides "partial" functions for manual currying
  • 26. from functools import reduce import operator import random def two_random_sum(): return reduce(operator.sum, [random.random()]*2) def three_random_product(): return reduce(operator.mul, [random.random()]*3) def four_random_sub(): return reduce(operator.sub, [random.random()]*4) def five_random_pow (): return reduce(operator.pow, [random.random()]*5)
  • 27. def handle_random_numbers(size, function): return reduce(function, [random.random()]*size) two_random_sum = partial(handle_random_numbers, size=2) three_random_sum = partial(handle_random_numbers, size=3) two_random_pow = partial(handle_random_numbers, size=2, function=operator.pow) five_random_product = partial(handle_random_numbers, size=5, function=operator.mul)
  • 28. Decorator Pattern Return a modified version of a decorated function
  • 29. from functools import wraps from functools import partial def get_ned_data(n): def get_doubled_data(func, *args, **kwargs): @wraps(func) def _inner(*args, **kwargs): kwargs["new_param"] = kwargs["some_param"]*n return func(*args, **kwargs) return _inner return get_doubled_data
  • 30. @get_ned_data(n=2) def double_func(*args, **kwargs): assert(kwargs["new_param"] == kwargs["some_param"]*2) @get_ned_data(n=3) def triple_func(*args, **kwargs): assert(kwargs["new_param"] == kwargs["some_param"]*3) double_func(some_param=3) triple_func(some_param=5)
  • 31. Monads • How to handle errors in functional programming? • Practical example: parsing and transforming data coming from HTTP request • Python "std" libs have no support
  • 32. from fn.monad import optionable def get(request, *args, **kwargs): @optionable def _get_values(data): return data.get("values", None) _split = lambda item: item.split(",") _strip = lambda item: item.replace(" ", "") _filter = lambda item: list(filter(lambda i: i, item)) values = _get_values(request.GET).map(_strip).map(_split).map(_filter).get_or(["v1,v2"]) return values
  • 33. from collections import namedtuple def test(): _req_class = namedtuple("Request", ("GET")) request_1 = _req_class(dict(values="v1, v2,v3")) request_2 = _req_class(dict(values="v1,v2,v3 ")) request_3 = _req_class(dict(values="v1, v2,v3, ")) assert(get(request_1) == ['v1', 'v2', 'v3']) assert(get(request_2) == ['v1', 'v2', 'v3']) assert(get(request_3) == ['v1', 'v2', 'v3'])
  • 34. @get_object(MeterInstance) def post(self, request, *args, **kwargs): @optionable def get_data(data): return data.get("data", None) return get_data(request.DATA) .map( lambda item: handle_error_configuration(item, kwargs["contatore"])) .map( lambda item: Response(dict(detail=item), status=200)) .get_or(Response("BadRequest", status=400))
  • 35. Useful libraries • Fn.py (https://github.com/kachayev/fn.py) (A bit of Scala, ported to Python) • Underscore.py (ported from underscore_js)
  • 36. Summary • Functional programming for writing more succint code • Change viewpoint: think in terms of functions • Python seems for dummies until you show some cool features • Python can be slow but with a fine tuning can be more efficient