SlideShare a Scribd company logo
AN OVERVIEW OF
FUNCTIONAL
PROGRAMMING IN PYTHON
Edward D. Weinberger, Ph.D, F.R.M.
Adjunct Professor
NYU Tandon School of Engineering
edw@wpq-inc.com
ULTIMATE PURPOSE
To avoid
dysfunctional
programming!
OUTLINE
โ€ข Functional programming: definition and
advantages
โ€ข Functional programming: key concepts
โ€ข Python support for functional programming:
the basics and beyond
โ€ข Potential pitfalls and best practices
FUNCTIONAL
PROGRAMMING DEFINED
โ€œA programming paradigm that
treats computation as the
evaluation of mathematical
functions, avoiding changes of
state and mutable dataโ€
IMPLICATIONS OF
DEFINITION
โ€ข Output values of functions must depend
only on inputs, not on internal state
variables
โ€ข Calling a function twice with the same
inputs results in the same output
โ€œIMPERATIVE
PROGRAMMINGโ€ NO-NOโ€™s
โ€ข For/While Loops
โ€ข Internal โ€œstateโ€ variables (e.g. variables
assigned in __init__() and updated by other
methods)
โ€ข Re-assignment (mutability) of variables
OBVIOUS QUESTION:
Why bother???
IMPERATIVE VERSION OF
QUICKSORT
def quicksort(array):
indexes_stack = list()
idx = (0, len(array) - 1)
indexes_stack.append(idx)
for idx in indexes_stack:
elem_idx = idx[0]
pivot_idx = idx[1]
while pivot_idx > elem_idx:
pivot = array[pivot_idx]
elem = array[elem_idx]
if elem > pivot:
array[pivot_idx] = elem
array[elem_idx] = array[pivot_idx - 1]
array[pivot_idx - 1] = pivot
pivot_idx -= 1
else:
elem_idx += 1
boundar_low = idx[0]
boundar_high = idx[1]
if pivot_idx > 1 and boundar_low < pivot_idx - 1:
indexes_stack.append((boundar_low, pivot_idx - 1))
if pivot_idx < len(array) -1 and pivot_idx + 1 < boundar_high:
indexes_stack.append((pivot_idx + 1, boundar_high))
return array
FUNCTIONAL VERSION OF
QUICKSORT
def quicksort(lst):
if len(lst) == 0:
return lst
pivots = list(filter(lambda x: x == lst[0], lst))
small = quicksort(list(filter(lambda x: x < lst[0], lst)))
large = quicksort(list(filter(lambda x: x > lst[0], lst)))
return small + pivots + large
OTHER ADVANTAGES
(besides ease of reading/debugging)
โ€ข May facilitate
โ€ข Compiler optimization
โ€ข Parallelization
โ€ข Faster execution via memorization
โ€ข Lazy evaluation
โ€ข Academic studies of formal proofs of
program correctness have made
progress under functional programming
assumptions
FUNCTIONAL
PROGRAMMING: A FEW
KEY CONCEPTS
PURE FUNCTIONS
โ€ข Functions that
โ€ข always return the same result, given the same
argument, so sin(x) is pure, today() is impure
โ€ข do not have โ€œside effectsโ€
โ€ข Cannot use internal state to determine
what result to return
โ€ข Python functions may or may not be pure
REFERENTIAL
TRANSPARENCY
โ€ข Describes a function/expression that can be
replaced by its value without changing the
behavior of a program in which it is
embedded (e.g. sin(x)+5)
โ€ข Generally, an expression can only be
referentially transparent if any functions
used are pure
โ€œHIGHER ORDERโ€
FUNCTIONS
โ€ข Functions that take other functions as
inputs and/or outputs
โ€ข Python examples:
โ€ข Pythonโ€™s sorted function takes a key parameter,
the name of a function that returns a sort key
โ€ข A GUI button objectโ€™s __init__() might be
passed the name of the function to be executed
when the button is clicked
PYTHON SUPPORT FOR
FUNCTIONAL
PROGRAMMING
SUPPORT FOR FP IN
โ€œEVERY DAYโ€ PYTHON
โ€ข Recursion
โ€ข Lambda expressions
โ€ข All functions are โ€œfirst class functionsโ€, i.e.
function names can be
โ€ข passed as arguments
โ€ข assigned to variables
โ€ข appear as elements of lists
โ€ข etc.
PYTHON ITERABLES
AND ITERATORS
โ€ข An iterable is an object that defines either a
__getitem__() or an __iter__() method
โ€ข The built-in function iter(iterable) returns
an iterator (also returned by generators)
โ€ข Iterators define a (private) __next__()
method, called by the built-in function
next(), raising the StopIteration error
when nothing is next
ITERABLE/ITERATOR
EXAMPLE
>>> aList = [1, 2] #need not be a list
>>> aListIter = iter(aList) #possibly
>>> next(aListIter)# lazy evaluation
1
>>> next(aListIter)#
2
>>> next(aListIter)
StopIteration Traceback โ€ฆ
Returns an iterator which is the result of
applying <function> (of one argument) to
successive individual items supplied by
<iterable>
EXAMPLE:
>>> list(map(lambda x: x*x,[1,3,5,7]))
[1, 9, 25, 49]
map(<function>, <iterable>)
MAP RETURNS AN
ITERATOR
>>> seq = map(lambda x: x*x, [1, 3, 5, 7])
>>> seq
<map at 0xโ€ฆ>
>>> next(seq)
1
>>> next(seq)
9
applies <function> (of two arguments) to the
first two items supplied by <iterable>, thus
โ€œreducingโ€ them to a single value. This result
is supplied, along with the third item from
<iterable> thus โ€œreducingโ€ all three items to
a single value
Note: reduce must be imported from the
built-in library functools
reduce(<function>, <iterable>)
WORKING WITH reduce
>>> from functools import reduce
>>> reduce(lambda x,y: x*y, range(1, 6))
120 #The product of ((1*2)*3)*4)*5
Constructs an iterator for those elements of
<iterable> for which <function> returns True
Equivalent to the generator expression
(for item in <iterable>
item if <function>(item)
)
filter(<function>, <iterable>)
WORKING WITH filter
>>> isEven = lambda x: (x%2 == 0)
>>> yetAnotherList = [12, 43, 33, 32, 31]
>>> it = filter(isEven, yetAnotherList)
>>> next(it)
12
>>> next(it)
32
>>> list(filter(isEven, yetAnotherList))
[12, 32]
AN EXTENDED EXAMPLE
min_order = 100
invoice_totals = list(
map(lambda x: x if x[1] >= min_order
else (x[0], x[1] + 10),
map(lambda x: (x[0],x[2] * x[3]), orders)))
WHAT ELSE IS THERE TO
KNOW?
โ€ข More jargon (see Wikipedia)
โ€ข The operator, functools and itertools
libraries
โ€ข Various ideas about pitfalls/best practices
PITFALLS/BEST
PRACTICES IN
FUNCTIONAL
PROGRAMMING
BIGGEST PITFALL:
โ€œItโ€™s the new kid on the block!
โ€ข After 60+ years,
โ€ข Imperative programming (IP) is well understood
โ€ข Lots of hardware and compiler support for IP
โ€ข IP code has large code base
RECURSION IS
PROBLEMATIC
โ€ข Recursion is always relatively slow and
memory intensive because of the many
subroutine calls usually required
โ€ข Python, in particular, only grudgingly
supports recursion
โ€ข Implementation not particularly fast
โ€ข Finite recursion depth, even for tail recursion
FP โ€œUpdate as you copyโ€
PARADIGM PROBLEMATIC
โ€ข The alternative to updating mutable
variables is โ€œupdate as you copyโ€
โ€ข โ€œUpdate as you copyโ€ leads to memory
bloat
โ€ข Can be difficult to keep track of whatโ€™s
going on if nested objects are being
copied/updated
FP โ€œUpdate as you copyโ€
PARADIGM PROBLEMATIC
โ€ข The alternative to updating mutable
variables is โ€œupdate as you copyโ€
โ€ข โ€œUpdate as you copyโ€ leads to memory
bloat
โ€ข Can be difficult to keep track of whatโ€™s
going on if nested objects are being
copied/updated
PURE FUNCTIONS AND I/O
DONโ€™T REALLY MIX
โ€ข Python functions such as input()are not
even close to referentially transparent!
โ€ข Internal state variables needed for buffered
reads/writes
BEST PRACTICES SPECIFIC TO
FUNCTIONAL PROGRAMMING
โ€ข Use map, reduce, filter, and other library
functions in place of recursion if possible
โ€ข Cleanly separate pure functions from
intrinsically impure functions (such as I/O)
โ€ข Combine related functions in a class and
use inheritance (yes, FP and OO do mix!)
BEST PRACTICES APPLICABLE TO
ALL PYTHON PROGRAMMING
โ€ข โ€œshort and sweetโ€ functions, doing one
thing well (1 or 2 ISO/ANSI 24x80 screens)
โ€ข Take advantage of Pythonโ€™s polymorphism
โ€ข Donโ€™t pack too much into a single line of
code
โ€ข Use descriptive variable names
BEST PRACTICES PER โ€œTHE ZEN
OF PYTHONโ€
โ€ข โ€œโ€ฆ practicality beats purityโ€
โ€ข โ€œReadability countsโ€
โ€ข โ€œIf an implementation is hard to explain, itโ€™s
a bad ideaโ€
โ€ข โ€œIf an implementation is easy to explain, it
might be a good ideaโ€
RECAP
โ€ข Functional programming: definition and
advantages
โ€ข Functional programming: key concepts
โ€ข Python support for functional programming:
the basics and beyond
โ€ข Potential pitfalls and best practices
Ad

More Related Content

What's hot (20)

Function
Function Function
Function
Kathmandu University
ย 
User defined functions
User defined functionsUser defined functions
User defined functions
Randy Riness @ South Puget Sound Community College
ย 
Functions assignment
Functions assignmentFunctions assignment
Functions assignment
Ahmad Kamal
ย 
Python algorithm
Python algorithmPython algorithm
Python algorithm
Prof. Dr. K. Adisesha
ย 
Functions in C
Functions in CFunctions in C
Functions in C
Kamal Acharya
ย 
User defined functions
User defined functionsUser defined functions
User defined functions
Rokonuzzaman Rony
ย 
c.p function
c.p functionc.p function
c.p function
giri5624
ย 
Functional programming in clojure
Functional programming in clojureFunctional programming in clojure
Functional programming in clojure
Juan-Manuel Gimeno
ย 
Functions in C - Programming
Functions in C - Programming Functions in C - Programming
Functions in C - Programming
GaurangVishnoi
ย 
FUNCTION CPU
FUNCTION CPUFUNCTION CPU
FUNCTION CPU
Krushal Kakadia
ย 
User defined functions in C programmig
User defined functions in C programmigUser defined functions in C programmig
User defined functions in C programmig
Appili Vamsi Krishna
ย 
Functions in C
Functions in CFunctions in C
Functions in C
Shobhit Upadhyay
ย 
User defined functions.1
User defined functions.1User defined functions.1
User defined functions.1
Mohammad Zuber Vohra
ย 
Functions
FunctionsFunctions
Functions
Online
ย 
Presentation on Function in C Programming
Presentation on Function in C ProgrammingPresentation on Function in C Programming
Presentation on Function in C Programming
Shuvongkor Barman
ย 
structured programming
structured programmingstructured programming
structured programming
Ahmad54321
ย 
Python functions
Python functionsPython functions
Python functions
Prof. Dr. K. Adisesha
ย 
Functions
Functions Functions
Functions
Dr.Subha Krishna
ย 
Functions in c
Functions in cFunctions in c
Functions in c
sunila tharagaturi
ย 
Functions in Python
Functions in PythonFunctions in Python
Functions in Python
Shakti Singh Rathore
ย 

Similar to Functional programming in python (20)

SENG 208 Week -5 Python Functions Presentation
SENG 208 Week -5 Python Functions PresentationSENG 208 Week -5 Python Functions Presentation
SENG 208 Week -5 Python Functions Presentation
AlpaslanERDA
ย 
3-Python Functions.pdf in simple.........
3-Python Functions.pdf in simple.........3-Python Functions.pdf in simple.........
3-Python Functions.pdf in simple.........
mxdsnaps
ย 
358 33 powerpoint-slides_2-functions_chapter-2
358 33 powerpoint-slides_2-functions_chapter-2358 33 powerpoint-slides_2-functions_chapter-2
358 33 powerpoint-slides_2-functions_chapter-2
sumitbardhan
ย 
Introduction to Functional Programming
Introduction to Functional ProgrammingIntroduction to Functional Programming
Introduction to Functional Programming
Francesco Bruni
ย 
Python functional programming
Python functional programmingPython functional programming
Python functional programming
Geison Goes
ย 
Intro to JavaScript - Week 2: Function
Intro to JavaScript - Week 2: FunctionIntro to JavaScript - Week 2: Function
Intro to JavaScript - Week 2: Function
Jeongbae Oh
ย 
Booting into functional programming
Booting into functional programmingBooting into functional programming
Booting into functional programming
Dhaval Dalal
ย 
Basics of Functional Programming
Basics of Functional ProgrammingBasics of Functional Programming
Basics of Functional Programming
Sartaj Singh
ย 
Function in C Programming
Function in C ProgrammingFunction in C Programming
Function in C Programming
Anil Pokhrel
ย 
Lecture 1_Functions in C.pptx
Lecture 1_Functions in C.pptxLecture 1_Functions in C.pptx
Lecture 1_Functions in C.pptx
KhurramKhan173
ย 
Functional Programming for OO Programmers (part 1)
Functional Programming for OO Programmers (part 1)Functional Programming for OO Programmers (part 1)
Functional Programming for OO Programmers (part 1)
Calvin Cheng
ย 
Functions_new.pptx
Functions_new.pptxFunctions_new.pptx
Functions_new.pptx
Yagna15
ย 
User_Defined_Functions_ppt_slideshare.
User_Defined_Functions_ppt_slideshare.User_Defined_Functions_ppt_slideshare.
User_Defined_Functions_ppt_slideshare.
NabeelaNousheen
ย 
Chapter One Function.pptx
Chapter One Function.pptxChapter One Function.pptx
Chapter One Function.pptx
miki304759
ย 
C Language Lecture 15
C Language Lecture 15C Language Lecture 15
C Language Lecture 15
Shahzaib Ajmal
ย 
Mastering Python lesson 4_functions_parameters_arguments
Mastering Python lesson 4_functions_parameters_argumentsMastering Python lesson 4_functions_parameters_arguments
Mastering Python lesson 4_functions_parameters_arguments
Ruth Marvin
ย 
Functions
FunctionsFunctions
Functions
Lakshmi Sarvani Videla
ย 
662213141-Tuxdoc-com-Programming-in-c-Reema-Thareja.pdf
662213141-Tuxdoc-com-Programming-in-c-Reema-Thareja.pdf662213141-Tuxdoc-com-Programming-in-c-Reema-Thareja.pdf
662213141-Tuxdoc-com-Programming-in-c-Reema-Thareja.pdf
ManiMala75
ย 
Functional Python Webinar from October 22nd, 2014
Functional Python Webinar from October 22nd, 2014Functional Python Webinar from October 22nd, 2014
Functional Python Webinar from October 22nd, 2014
Reuven Lerner
ย 
Introduction of function in c programming.pptx
Introduction of function in c programming.pptxIntroduction of function in c programming.pptx
Introduction of function in c programming.pptx
abhajgude
ย 
SENG 208 Week -5 Python Functions Presentation
SENG 208 Week -5 Python Functions PresentationSENG 208 Week -5 Python Functions Presentation
SENG 208 Week -5 Python Functions Presentation
AlpaslanERDA
ย 
3-Python Functions.pdf in simple.........
3-Python Functions.pdf in simple.........3-Python Functions.pdf in simple.........
3-Python Functions.pdf in simple.........
mxdsnaps
ย 
358 33 powerpoint-slides_2-functions_chapter-2
358 33 powerpoint-slides_2-functions_chapter-2358 33 powerpoint-slides_2-functions_chapter-2
358 33 powerpoint-slides_2-functions_chapter-2
sumitbardhan
ย 
Introduction to Functional Programming
Introduction to Functional ProgrammingIntroduction to Functional Programming
Introduction to Functional Programming
Francesco Bruni
ย 
Python functional programming
Python functional programmingPython functional programming
Python functional programming
Geison Goes
ย 
Intro to JavaScript - Week 2: Function
Intro to JavaScript - Week 2: FunctionIntro to JavaScript - Week 2: Function
Intro to JavaScript - Week 2: Function
Jeongbae Oh
ย 
Booting into functional programming
Booting into functional programmingBooting into functional programming
Booting into functional programming
Dhaval Dalal
ย 
Basics of Functional Programming
Basics of Functional ProgrammingBasics of Functional Programming
Basics of Functional Programming
Sartaj Singh
ย 
Function in C Programming
Function in C ProgrammingFunction in C Programming
Function in C Programming
Anil Pokhrel
ย 
Lecture 1_Functions in C.pptx
Lecture 1_Functions in C.pptxLecture 1_Functions in C.pptx
Lecture 1_Functions in C.pptx
KhurramKhan173
ย 
Functional Programming for OO Programmers (part 1)
Functional Programming for OO Programmers (part 1)Functional Programming for OO Programmers (part 1)
Functional Programming for OO Programmers (part 1)
Calvin Cheng
ย 
Functions_new.pptx
Functions_new.pptxFunctions_new.pptx
Functions_new.pptx
Yagna15
ย 
User_Defined_Functions_ppt_slideshare.
User_Defined_Functions_ppt_slideshare.User_Defined_Functions_ppt_slideshare.
User_Defined_Functions_ppt_slideshare.
NabeelaNousheen
ย 
Chapter One Function.pptx
Chapter One Function.pptxChapter One Function.pptx
Chapter One Function.pptx
miki304759
ย 
C Language Lecture 15
C Language Lecture 15C Language Lecture 15
C Language Lecture 15
Shahzaib Ajmal
ย 
Mastering Python lesson 4_functions_parameters_arguments
Mastering Python lesson 4_functions_parameters_argumentsMastering Python lesson 4_functions_parameters_arguments
Mastering Python lesson 4_functions_parameters_arguments
Ruth Marvin
ย 
662213141-Tuxdoc-com-Programming-in-c-Reema-Thareja.pdf
662213141-Tuxdoc-com-Programming-in-c-Reema-Thareja.pdf662213141-Tuxdoc-com-Programming-in-c-Reema-Thareja.pdf
662213141-Tuxdoc-com-Programming-in-c-Reema-Thareja.pdf
ManiMala75
ย 
Functional Python Webinar from October 22nd, 2014
Functional Python Webinar from October 22nd, 2014Functional Python Webinar from October 22nd, 2014
Functional Python Webinar from October 22nd, 2014
Reuven Lerner
ย 
Introduction of function in c programming.pptx
Introduction of function in c programming.pptxIntroduction of function in c programming.pptx
Introduction of function in c programming.pptx
abhajgude
ย 
Ad

Recently uploaded (20)

Solidworks Crack 2025 latest new + license code
Solidworks Crack 2025 latest new + license codeSolidworks Crack 2025 latest new + license code
Solidworks Crack 2025 latest new + license code
aneelaramzan63
ย 
Get & Download Wondershare Filmora Crack Latest [2025]
Get & Download Wondershare Filmora Crack Latest [2025]Get & Download Wondershare Filmora Crack Latest [2025]
Get & Download Wondershare Filmora Crack Latest [2025]
saniaaftab72555
ย 
Why Orangescrum Is a Game Changer for Construction Companies in 2025
Why Orangescrum Is a Game Changer for Construction Companies in 2025Why Orangescrum Is a Game Changer for Construction Companies in 2025
Why Orangescrum Is a Game Changer for Construction Companies in 2025
Orangescrum
ย 
Adobe Lightroom Classic Crack FREE Latest link 2025
Adobe Lightroom Classic Crack FREE Latest link 2025Adobe Lightroom Classic Crack FREE Latest link 2025
Adobe Lightroom Classic Crack FREE Latest link 2025
kashifyounis067
ย 
Adobe Illustrator Crack FREE Download 2025 Latest Version
Adobe Illustrator Crack FREE Download 2025 Latest VersionAdobe Illustrator Crack FREE Download 2025 Latest Version
Adobe Illustrator Crack FREE Download 2025 Latest Version
kashifyounis067
ย 
PDF Reader Pro Crack Latest Version FREE Download 2025
PDF Reader Pro Crack Latest Version FREE Download 2025PDF Reader Pro Crack Latest Version FREE Download 2025
PDF Reader Pro Crack Latest Version FREE Download 2025
mu394968
ย 
F-Secure Freedome VPN 2025 Crack Plus Activation New Version
F-Secure Freedome VPN 2025 Crack Plus Activation  New VersionF-Secure Freedome VPN 2025 Crack Plus Activation  New Version
F-Secure Freedome VPN 2025 Crack Plus Activation New Version
saimabibi60507
ย 
Not So Common Memory Leaks in Java Webinar
Not So Common Memory Leaks in Java WebinarNot So Common Memory Leaks in Java Webinar
Not So Common Memory Leaks in Java Webinar
Tier1 app
ย 
Top 10 Client Portal Software Solutions for 2025.docx
Top 10 Client Portal Software Solutions for 2025.docxTop 10 Client Portal Software Solutions for 2025.docx
Top 10 Client Portal Software Solutions for 2025.docx
Portli
ย 
Adobe Master Collection CC Crack Advance Version 2025
Adobe Master Collection CC Crack Advance Version 2025Adobe Master Collection CC Crack Advance Version 2025
Adobe Master Collection CC Crack Advance Version 2025
kashifyounis067
ย 
Douwan Crack 2025 new verson+ License code
Douwan Crack 2025 new verson+ License codeDouwan Crack 2025 new verson+ License code
Douwan Crack 2025 new verson+ License code
aneelaramzan63
ย 
FL Studio Producer Edition Crack 2025 Full Version
FL Studio Producer Edition Crack 2025 Full VersionFL Studio Producer Edition Crack 2025 Full Version
FL Studio Producer Edition Crack 2025 Full Version
tahirabibi60507
ย 
Explaining GitHub Actions Failures with Large Language Models Challenges, In...
Explaining GitHub Actions Failures with Large Language Models Challenges, In...Explaining GitHub Actions Failures with Large Language Models Challenges, In...
Explaining GitHub Actions Failures with Large Language Models Challenges, In...
ssuserb14185
ย 
Download YouTube By Click 2025 Free Full Activated
Download YouTube By Click 2025 Free Full ActivatedDownload YouTube By Click 2025 Free Full Activated
Download YouTube By Click 2025 Free Full Activated
saniamalik72555
ย 
The Significance of Hardware in Information Systems.pdf
The Significance of Hardware in Information Systems.pdfThe Significance of Hardware in Information Systems.pdf
The Significance of Hardware in Information Systems.pdf
drewplanas10
ย 
Download Wondershare Filmora Crack [2025] With Latest
Download Wondershare Filmora Crack [2025] With LatestDownload Wondershare Filmora Crack [2025] With Latest
Download Wondershare Filmora Crack [2025] With Latest
tahirabibi60507
ย 
EASEUS Partition Master Crack + License Code
EASEUS Partition Master Crack + License CodeEASEUS Partition Master Crack + License Code
EASEUS Partition Master Crack + License Code
aneelaramzan63
ย 
Kubernetes_101_Zero_to_Platform_Engineer.pptx
Kubernetes_101_Zero_to_Platform_Engineer.pptxKubernetes_101_Zero_to_Platform_Engineer.pptx
Kubernetes_101_Zero_to_Platform_Engineer.pptx
CloudScouts
ย 
Adobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage Dashboards
Adobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage DashboardsAdobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage Dashboards
Adobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage Dashboards
BradBedford3
ย 
Revolutionizing Residential Wi-Fi PPT.pptx
Revolutionizing Residential Wi-Fi PPT.pptxRevolutionizing Residential Wi-Fi PPT.pptx
Revolutionizing Residential Wi-Fi PPT.pptx
nidhisingh691197
ย 
Solidworks Crack 2025 latest new + license code
Solidworks Crack 2025 latest new + license codeSolidworks Crack 2025 latest new + license code
Solidworks Crack 2025 latest new + license code
aneelaramzan63
ย 
Get & Download Wondershare Filmora Crack Latest [2025]
Get & Download Wondershare Filmora Crack Latest [2025]Get & Download Wondershare Filmora Crack Latest [2025]
Get & Download Wondershare Filmora Crack Latest [2025]
saniaaftab72555
ย 
Why Orangescrum Is a Game Changer for Construction Companies in 2025
Why Orangescrum Is a Game Changer for Construction Companies in 2025Why Orangescrum Is a Game Changer for Construction Companies in 2025
Why Orangescrum Is a Game Changer for Construction Companies in 2025
Orangescrum
ย 
Adobe Lightroom Classic Crack FREE Latest link 2025
Adobe Lightroom Classic Crack FREE Latest link 2025Adobe Lightroom Classic Crack FREE Latest link 2025
Adobe Lightroom Classic Crack FREE Latest link 2025
kashifyounis067
ย 
Adobe Illustrator Crack FREE Download 2025 Latest Version
Adobe Illustrator Crack FREE Download 2025 Latest VersionAdobe Illustrator Crack FREE Download 2025 Latest Version
Adobe Illustrator Crack FREE Download 2025 Latest Version
kashifyounis067
ย 
PDF Reader Pro Crack Latest Version FREE Download 2025
PDF Reader Pro Crack Latest Version FREE Download 2025PDF Reader Pro Crack Latest Version FREE Download 2025
PDF Reader Pro Crack Latest Version FREE Download 2025
mu394968
ย 
F-Secure Freedome VPN 2025 Crack Plus Activation New Version
F-Secure Freedome VPN 2025 Crack Plus Activation  New VersionF-Secure Freedome VPN 2025 Crack Plus Activation  New Version
F-Secure Freedome VPN 2025 Crack Plus Activation New Version
saimabibi60507
ย 
Not So Common Memory Leaks in Java Webinar
Not So Common Memory Leaks in Java WebinarNot So Common Memory Leaks in Java Webinar
Not So Common Memory Leaks in Java Webinar
Tier1 app
ย 
Top 10 Client Portal Software Solutions for 2025.docx
Top 10 Client Portal Software Solutions for 2025.docxTop 10 Client Portal Software Solutions for 2025.docx
Top 10 Client Portal Software Solutions for 2025.docx
Portli
ย 
Adobe Master Collection CC Crack Advance Version 2025
Adobe Master Collection CC Crack Advance Version 2025Adobe Master Collection CC Crack Advance Version 2025
Adobe Master Collection CC Crack Advance Version 2025
kashifyounis067
ย 
Douwan Crack 2025 new verson+ License code
Douwan Crack 2025 new verson+ License codeDouwan Crack 2025 new verson+ License code
Douwan Crack 2025 new verson+ License code
aneelaramzan63
ย 
FL Studio Producer Edition Crack 2025 Full Version
FL Studio Producer Edition Crack 2025 Full VersionFL Studio Producer Edition Crack 2025 Full Version
FL Studio Producer Edition Crack 2025 Full Version
tahirabibi60507
ย 
Explaining GitHub Actions Failures with Large Language Models Challenges, In...
Explaining GitHub Actions Failures with Large Language Models Challenges, In...Explaining GitHub Actions Failures with Large Language Models Challenges, In...
Explaining GitHub Actions Failures with Large Language Models Challenges, In...
ssuserb14185
ย 
Download YouTube By Click 2025 Free Full Activated
Download YouTube By Click 2025 Free Full ActivatedDownload YouTube By Click 2025 Free Full Activated
Download YouTube By Click 2025 Free Full Activated
saniamalik72555
ย 
The Significance of Hardware in Information Systems.pdf
The Significance of Hardware in Information Systems.pdfThe Significance of Hardware in Information Systems.pdf
The Significance of Hardware in Information Systems.pdf
drewplanas10
ย 
Download Wondershare Filmora Crack [2025] With Latest
Download Wondershare Filmora Crack [2025] With LatestDownload Wondershare Filmora Crack [2025] With Latest
Download Wondershare Filmora Crack [2025] With Latest
tahirabibi60507
ย 
EASEUS Partition Master Crack + License Code
EASEUS Partition Master Crack + License CodeEASEUS Partition Master Crack + License Code
EASEUS Partition Master Crack + License Code
aneelaramzan63
ย 
Kubernetes_101_Zero_to_Platform_Engineer.pptx
Kubernetes_101_Zero_to_Platform_Engineer.pptxKubernetes_101_Zero_to_Platform_Engineer.pptx
Kubernetes_101_Zero_to_Platform_Engineer.pptx
CloudScouts
ย 
Adobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage Dashboards
Adobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage DashboardsAdobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage Dashboards
Adobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage Dashboards
BradBedford3
ย 
Revolutionizing Residential Wi-Fi PPT.pptx
Revolutionizing Residential Wi-Fi PPT.pptxRevolutionizing Residential Wi-Fi PPT.pptx
Revolutionizing Residential Wi-Fi PPT.pptx
nidhisingh691197
ย 
Ad

Functional programming in python

  • 1. AN OVERVIEW OF FUNCTIONAL PROGRAMMING IN PYTHON Edward D. Weinberger, Ph.D, F.R.M. Adjunct Professor NYU Tandon School of Engineering [email protected]
  • 3. OUTLINE โ€ข Functional programming: definition and advantages โ€ข Functional programming: key concepts โ€ข Python support for functional programming: the basics and beyond โ€ข Potential pitfalls and best practices
  • 4. FUNCTIONAL PROGRAMMING DEFINED โ€œA programming paradigm that treats computation as the evaluation of mathematical functions, avoiding changes of state and mutable dataโ€
  • 5. IMPLICATIONS OF DEFINITION โ€ข Output values of functions must depend only on inputs, not on internal state variables โ€ข Calling a function twice with the same inputs results in the same output
  • 6. โ€œIMPERATIVE PROGRAMMINGโ€ NO-NOโ€™s โ€ข For/While Loops โ€ข Internal โ€œstateโ€ variables (e.g. variables assigned in __init__() and updated by other methods) โ€ข Re-assignment (mutability) of variables
  • 8. IMPERATIVE VERSION OF QUICKSORT def quicksort(array): indexes_stack = list() idx = (0, len(array) - 1) indexes_stack.append(idx) for idx in indexes_stack: elem_idx = idx[0] pivot_idx = idx[1] while pivot_idx > elem_idx: pivot = array[pivot_idx] elem = array[elem_idx] if elem > pivot: array[pivot_idx] = elem array[elem_idx] = array[pivot_idx - 1] array[pivot_idx - 1] = pivot pivot_idx -= 1 else: elem_idx += 1 boundar_low = idx[0] boundar_high = idx[1] if pivot_idx > 1 and boundar_low < pivot_idx - 1: indexes_stack.append((boundar_low, pivot_idx - 1)) if pivot_idx < len(array) -1 and pivot_idx + 1 < boundar_high: indexes_stack.append((pivot_idx + 1, boundar_high)) return array
  • 9. FUNCTIONAL VERSION OF QUICKSORT def quicksort(lst): if len(lst) == 0: return lst pivots = list(filter(lambda x: x == lst[0], lst)) small = quicksort(list(filter(lambda x: x < lst[0], lst))) large = quicksort(list(filter(lambda x: x > lst[0], lst))) return small + pivots + large
  • 10. OTHER ADVANTAGES (besides ease of reading/debugging) โ€ข May facilitate โ€ข Compiler optimization โ€ข Parallelization โ€ข Faster execution via memorization โ€ข Lazy evaluation โ€ข Academic studies of formal proofs of program correctness have made progress under functional programming assumptions
  • 12. PURE FUNCTIONS โ€ข Functions that โ€ข always return the same result, given the same argument, so sin(x) is pure, today() is impure โ€ข do not have โ€œside effectsโ€ โ€ข Cannot use internal state to determine what result to return โ€ข Python functions may or may not be pure
  • 13. REFERENTIAL TRANSPARENCY โ€ข Describes a function/expression that can be replaced by its value without changing the behavior of a program in which it is embedded (e.g. sin(x)+5) โ€ข Generally, an expression can only be referentially transparent if any functions used are pure
  • 14. โ€œHIGHER ORDERโ€ FUNCTIONS โ€ข Functions that take other functions as inputs and/or outputs โ€ข Python examples: โ€ข Pythonโ€™s sorted function takes a key parameter, the name of a function that returns a sort key โ€ข A GUI button objectโ€™s __init__() might be passed the name of the function to be executed when the button is clicked
  • 16. SUPPORT FOR FP IN โ€œEVERY DAYโ€ PYTHON โ€ข Recursion โ€ข Lambda expressions โ€ข All functions are โ€œfirst class functionsโ€, i.e. function names can be โ€ข passed as arguments โ€ข assigned to variables โ€ข appear as elements of lists โ€ข etc.
  • 17. PYTHON ITERABLES AND ITERATORS โ€ข An iterable is an object that defines either a __getitem__() or an __iter__() method โ€ข The built-in function iter(iterable) returns an iterator (also returned by generators) โ€ข Iterators define a (private) __next__() method, called by the built-in function next(), raising the StopIteration error when nothing is next
  • 18. ITERABLE/ITERATOR EXAMPLE >>> aList = [1, 2] #need not be a list >>> aListIter = iter(aList) #possibly >>> next(aListIter)# lazy evaluation 1 >>> next(aListIter)# 2 >>> next(aListIter) StopIteration Traceback โ€ฆ
  • 19. Returns an iterator which is the result of applying <function> (of one argument) to successive individual items supplied by <iterable> EXAMPLE: >>> list(map(lambda x: x*x,[1,3,5,7])) [1, 9, 25, 49] map(<function>, <iterable>)
  • 20. MAP RETURNS AN ITERATOR >>> seq = map(lambda x: x*x, [1, 3, 5, 7]) >>> seq <map at 0xโ€ฆ> >>> next(seq) 1 >>> next(seq) 9
  • 21. applies <function> (of two arguments) to the first two items supplied by <iterable>, thus โ€œreducingโ€ them to a single value. This result is supplied, along with the third item from <iterable> thus โ€œreducingโ€ all three items to a single value Note: reduce must be imported from the built-in library functools reduce(<function>, <iterable>)
  • 22. WORKING WITH reduce >>> from functools import reduce >>> reduce(lambda x,y: x*y, range(1, 6)) 120 #The product of ((1*2)*3)*4)*5
  • 23. Constructs an iterator for those elements of <iterable> for which <function> returns True Equivalent to the generator expression (for item in <iterable> item if <function>(item) ) filter(<function>, <iterable>)
  • 24. WORKING WITH filter >>> isEven = lambda x: (x%2 == 0) >>> yetAnotherList = [12, 43, 33, 32, 31] >>> it = filter(isEven, yetAnotherList) >>> next(it) 12 >>> next(it) 32 >>> list(filter(isEven, yetAnotherList)) [12, 32]
  • 25. AN EXTENDED EXAMPLE min_order = 100 invoice_totals = list( map(lambda x: x if x[1] >= min_order else (x[0], x[1] + 10), map(lambda x: (x[0],x[2] * x[3]), orders)))
  • 26. WHAT ELSE IS THERE TO KNOW? โ€ข More jargon (see Wikipedia) โ€ข The operator, functools and itertools libraries โ€ข Various ideas about pitfalls/best practices
  • 28. BIGGEST PITFALL: โ€œItโ€™s the new kid on the block! โ€ข After 60+ years, โ€ข Imperative programming (IP) is well understood โ€ข Lots of hardware and compiler support for IP โ€ข IP code has large code base
  • 29. RECURSION IS PROBLEMATIC โ€ข Recursion is always relatively slow and memory intensive because of the many subroutine calls usually required โ€ข Python, in particular, only grudgingly supports recursion โ€ข Implementation not particularly fast โ€ข Finite recursion depth, even for tail recursion
  • 30. FP โ€œUpdate as you copyโ€ PARADIGM PROBLEMATIC โ€ข The alternative to updating mutable variables is โ€œupdate as you copyโ€ โ€ข โ€œUpdate as you copyโ€ leads to memory bloat โ€ข Can be difficult to keep track of whatโ€™s going on if nested objects are being copied/updated
  • 31. FP โ€œUpdate as you copyโ€ PARADIGM PROBLEMATIC โ€ข The alternative to updating mutable variables is โ€œupdate as you copyโ€ โ€ข โ€œUpdate as you copyโ€ leads to memory bloat โ€ข Can be difficult to keep track of whatโ€™s going on if nested objects are being copied/updated
  • 32. PURE FUNCTIONS AND I/O DONโ€™T REALLY MIX โ€ข Python functions such as input()are not even close to referentially transparent! โ€ข Internal state variables needed for buffered reads/writes
  • 33. BEST PRACTICES SPECIFIC TO FUNCTIONAL PROGRAMMING โ€ข Use map, reduce, filter, and other library functions in place of recursion if possible โ€ข Cleanly separate pure functions from intrinsically impure functions (such as I/O) โ€ข Combine related functions in a class and use inheritance (yes, FP and OO do mix!)
  • 34. BEST PRACTICES APPLICABLE TO ALL PYTHON PROGRAMMING โ€ข โ€œshort and sweetโ€ functions, doing one thing well (1 or 2 ISO/ANSI 24x80 screens) โ€ข Take advantage of Pythonโ€™s polymorphism โ€ข Donโ€™t pack too much into a single line of code โ€ข Use descriptive variable names
  • 35. BEST PRACTICES PER โ€œTHE ZEN OF PYTHONโ€ โ€ข โ€œโ€ฆ practicality beats purityโ€ โ€ข โ€œReadability countsโ€ โ€ข โ€œIf an implementation is hard to explain, itโ€™s a bad ideaโ€ โ€ข โ€œIf an implementation is easy to explain, it might be a good ideaโ€
  • 36. RECAP โ€ข Functional programming: definition and advantages โ€ข Functional programming: key concepts โ€ข Python support for functional programming: the basics and beyond โ€ข Potential pitfalls and best practices