SlideShare a Scribd company logo
Functional Programming in Python
(PYTHON)( )
TODAY'S SLIDES
http://goo.gl/iRXD0Y
(PYTHON)( )
ABOUT ME
+ Colin Su a.k.a LittleQ
+ http://about.me/littleq
+ Productional Experience:
- Erlang
- Python
- Java{,Script}
(PYTHON)( )
PROGRAMMING IN PYTHON
+ Imperative Programming
- Shell Scripting
+ Procedural Programming
- Languages with functions
+ Declarative Programming
- Functional Programming
(PYTHON)( )
FUNCTIONAL PROGRAMMING
+ No state
+ Immutable data
+ Function as first-class citizen
+ Higher-order function
+ Purity
+ Recursion, tail recursion
+ ...the list is too long to name here
(PYTHON)( )
IP VS FP
$ ./program1
$ ./program2 --arg=1
$ ./program3
$ ./program1 | ./program2 --arg=1 | ./program3
Imperative Functional
Your Terminal
(PYTHON)( )
FUNCTION AS FIRST CLASS OBJ
def add(a, b):
return a + b
add2 = add
add2(1,2) # 3
def giveMeAdd():
def add(a, b):
return a + b
return add
(PYTHON)( )
LAMBDA SUPPORT
add = lambda a, b : a + b
minus = lambda a, b : a - b
multiply = lambda a, b : a * b
divide = lambda a, b : a / b
(PYTHON)( )
(POOR) LAMBDA SUPPORT
add = lambda a, b:
c = a + b
return c
(PYTHON)( )
(POOR) LAMBDA SUPPORT
add = lambda a, b:
c = a + b
return c
File "test.py", line 29
add = lambda a, b:
^
SyntaxError: invalid syntax
(PYTHON)( )
HIGHER-ORDER FUNCTION
+ Function eats functions, and returns functions
def food():
return "food got eaten"
drink = lambda: "drink got drunk"
def me(*args):
def eat():
return map(lambda x: x(), args)
return eat
act = me(food, drink)
print act()
>>> ['food got eaten', 'drink got drunk']
(PYTHON)( )
MAP/REDUCE/FILTER
+ A war between readability and conciseness
+ To make your code pluggable
(PYTHON)( )
CALCULATE "1++2+3+++4+5"
(PYTHON)( )
IMPERATIVE.PY
INPUT = "1+2++3+++4++5+6+7++8+9++10"
result = 0
for num in INPUT.split('+'):
if num:
result += int(num)
print result
Iterate on the same variable to perform task
(PYTHON)( )
FUNCTIONAL.PY
from operator import add
INPUT = "1+2++3+++4++5+6+7++8+9++10"
print reduce(add, map(int, filter(bool, INPUT.split('+'))))
(PYTHON)( )
FUNCTIONAL PYTHON
MADE SIMPLE
(PYTHON)( )
BUT NOT ALL LANGUAGES
DO...
(PYTHON)( )
IMPERATIVE.JAVA
Multiset<Integer> lengths = HashMultiset.create();
for (String string : strings) {
if (CharMatcher.JAVA_UPPER_CASE.matchesAllOf(string)) {
lengths.add(string.length());
}
}
Looks making sense
(PYTHON)( )
FUNCTIONAL.JAVA
Function<String, Integer> lengthFunction = new Function<String, Integer>() {
public Integer apply(String string) {
return string.length();
}
};
Predicate<String> allCaps = new Predicate<String>() {
public boolean apply(String string) {
return CharMatcher.JAVA_UPPER_CASE.matchesAllOf(string);
}
};
Multiset<Integer> lengths = HashMultiset.create(
Iterables.transform(Iterables.filter(strings, allCaps), lengthFunction));
(PYTHON)( )
WTF
(PYTHON)( )
Welcome To Functional
(PYTHON)( )
But my typing speed really got increased since using Java.
PARTIAL FUNCTION
APPLICATION
(((a × b) → c) × a) → (b → c)
(PYTHON)( )
PARTIAL FUNCTION
APPLICATION
from functools import partial
def f(x, y, z):
return x + y + z
f2 = partial(f, 100, 10)
print f2(5) #115
(PYTHON)( )
PARTIAL FUNCTION
APPLICATION
+ Keyword-based partial application
from functools import partial
from datetime import datetime
def log(message, prefix="", postfix=""):
print prefix, message, postfix
error = partial(log, postfix=datetime.now(), prefix="[ERROR]")
error("something goes wrong")
# [ERROR] something goes wrong 2014-04-10 01:37:07.250509
CURRYING
((a × b × c) → d) → (((a → b) → c) → d)
(PYTHON)( )
CURRYING
+ Simple sum
def simple_sum(a, b):
return sum(range(a, b+1))
>>> simple_sum(1, 10)
55
(PYTHON)( )
CURRYING
+ Squared sum
def square_sum(a, b):
return sum(map(lambda x: x**2, range(a,b+1)))
>>> square_sum(1,10)
385
(PYTHON)( )
CURRYING
+ Square root sum
def sqrt_sum(a, b):
return sum(map(math.sqrt, range(a,b+1)))
>>> sqrt_sum(1,10)
22.4682781862041
(PYTHON)( )
CURRYING
+ Curried sum()
import math
def fsum(f):
def apply(a, b):
return sum(map(f, range(a,b+1)))
return apply
simple_sum = fsum(int)
square_sum = fsum(lambda x: x**2)
sqrt_sum = fsum(math.sqrt)
print simple_sum(1,10) # 55
print square_sum(1,10) # 385
print sqrt_sum(1,10) # 22.4682781862
(PYTHON)( )
CURRYING
+ Combined with partial
def fsum(f):
def apply(a, b):
return sum(map(f, range(a,b+1)))
return apply
from functools import partial
from operator import mul
mul_sum = fsum(partial(mul, 2))
print mul_sum(1,10) # 110
(PYTHON)( )
DECORATOR
+ Another way to curry
import math
def fsum(f):
def apply(a, b):
return sum(map(f, range(a,b+1)))
return apply
@fsum
def sqrt_sum(x):
return math.sqrt(x)
print sqrt_sum(1,10) # 22.4682781862
(PYTHON)( )
GENERIC CURRY IN PYTHON
import functools
def curry(func):
def curried(*args, **kwargs):
if not args and not kwargs:
return func()
return curry(functools.partial(func, *args, **kwargs))
return curried
@curry
def add(a, b, c, d, e, f, g):
return a + b + c + d + e + f + g
add12 = add(1)(2)
add1234 = add12(3)(4)
add1234567 = add1234(5)(6)(7)
print add1234567() # 28
(PYTHON)( )
TAIL RECURSION
+ No grammar-level support, just simulation
def printAll(strings):
if strings:
print strings[0]
return printAll(strings[1:])
printAll([1,2,3,4,5])
Python 2
def printAll(strings):
if strings:
head, *tail = strings
print(head)
return printAll(tail)
printAll([1,2,3,4,5])
Python 3
(PYTHON)( )
SO?
(PYTHON)( )
FUNCTIONAL PYTHON?
Pros
+ First-class function
+ lambda
+ built-in map/filter/reduce
+ functools
+ generators as lazy-evaluation
Cons
+ non-pure
+ lambda (?)
+ memory-cost operations
+ No optimization for tail recursion
+ No pattern matching
(PYTHON)( )
CONCLUSION
+ Python is not for replacing any functional
language
+ But a good way to begin functional
programming
(PYTHON)( )
THINK FUNCTIONAL.
(PYTHON)( )
ALL CODE SAMPLES ON GIST
(PYTHON)( )
END
Questions

More Related Content

PPT
An Overview Of Python With Functional Programming
PDF
Thinking in Functions: Functional Programming in Python
PDF
Intro to Functional Programming
PPT
Introduction to Functional Programming in JavaScript
PDF
Functional Programming Patterns (BuildStuff '14)
PDF
Functional Python Webinar from October 22nd, 2014
PPTX
Functional programming in JavaScript
An Overview Of Python With Functional Programming
Thinking in Functions: Functional Programming in Python
Intro to Functional Programming
Introduction to Functional Programming in JavaScript
Functional Programming Patterns (BuildStuff '14)
Functional Python Webinar from October 22nd, 2014
Functional programming in JavaScript

What's hot (20)

PPTX
Functional Programming in Javascript - IL Tech Talks week
PDF
Functional Programming with JavaScript
PPTX
Advance python programming
PPTX
Functional Programming in JavaScript by Luis Atencio
PDF
Blazing Fast, Pure Effects without Monads — LambdaConf 2018
PPTX
C++ programming function
PDF
Learning Functional Programming Without Growing a Neckbeard
PPT
C++ functions presentation by DHEERAJ KATARIA
PDF
Java 8 Workshop
PPTX
Functions in C++
PDF
Declarative Type System Specification with Statix
PPT
C++ functions
PPTX
Functional programming
PDF
Data structure lab manual
PDF
Functional programming ii
PDF
Imugi: Compiler made with Python
PPT
lets play with "c"..!!! :):)
PPTX
functions
PDF
One Monad to Rule Them All
Functional Programming in Javascript - IL Tech Talks week
Functional Programming with JavaScript
Advance python programming
Functional Programming in JavaScript by Luis Atencio
Blazing Fast, Pure Effects without Monads — LambdaConf 2018
C++ programming function
Learning Functional Programming Without Growing a Neckbeard
C++ functions presentation by DHEERAJ KATARIA
Java 8 Workshop
Functions in C++
Declarative Type System Specification with Statix
C++ functions
Functional programming
Data structure lab manual
Functional programming ii
Imugi: Compiler made with Python
lets play with "c"..!!! :):)
functions
One Monad to Rule Them All
Ad

Viewers also liked (20)

PDF
Socket Programming In Python
PDF
Programming with Python and PostgreSQL
PDF
Programming with Python - Basic
PDF
Declarative Programming & Algebraic Data Types from Django's perspective
PPTX
Golang iran - tutorial go programming language - Preliminary
PDF
Golang #5: To Go or not to Go
PDF
Golang
PPTX
Paradigms
PPTX
Write microservice in golang
PDF
Develop Android app using Golang
PDF
Architecture Overview: Kubernetes with Red Hat Enterprise Linux 7.1
PPT
Securing Windows web servers
PPTX
Serial Killers Presentation1
PDF
Android UI
PDF
Functional style programming
PPTX
CITY OF SPIES BY SORAYYA KHAN
PDF
What is Network Security?
PPTX
Functional programming with python
PPTX
Carrick - Introduction to Physics & Electronics - Spring Review 2012
PPT
Socket Programming In Python
Programming with Python and PostgreSQL
Programming with Python - Basic
Declarative Programming & Algebraic Data Types from Django's perspective
Golang iran - tutorial go programming language - Preliminary
Golang #5: To Go or not to Go
Golang
Paradigms
Write microservice in golang
Develop Android app using Golang
Architecture Overview: Kubernetes with Red Hat Enterprise Linux 7.1
Securing Windows web servers
Serial Killers Presentation1
Android UI
Functional style programming
CITY OF SPIES BY SORAYYA KHAN
What is Network Security?
Functional programming with python
Carrick - Introduction to Physics & Electronics - Spring Review 2012
Ad

Similar to Functional programming in Python (20)

PDF
Pythonとはなんなのか?
PPTX
Function recap
PPTX
Function recap
PDF
2014 computer science_question_paper
PDF
Byterun, a Python bytecode interpreter - Allison Kaptur at NYCPython
DOCX
Basic python laboratoty_ PSPP Manual .docx
PDF
C++ normal assignments by maharshi_jd.pdf
PDF
Chapter 1 Basic Programming (Python Programming Lecture)
PDF
Phil Bartie QGIS PLPython
PDF
chapter3 (2).pdf
PDF
仕事で使うF#
PDF
All I know about rsc.io/c2go
PPT
PDF
3 kotlin vs. java- what kotlin has that java does not
PDF
Go: It's Not Just For Google
PDF
オープンデータを使ったモバイルアプリ開発(応用編)
PPTX
Modern technologies in data science
PDF
Implementing Software Machines in Go and C
PDF
Something about Golang
Pythonとはなんなのか?
Function recap
Function recap
2014 computer science_question_paper
Byterun, a Python bytecode interpreter - Allison Kaptur at NYCPython
Basic python laboratoty_ PSPP Manual .docx
C++ normal assignments by maharshi_jd.pdf
Chapter 1 Basic Programming (Python Programming Lecture)
Phil Bartie QGIS PLPython
chapter3 (2).pdf
仕事で使うF#
All I know about rsc.io/c2go
3 kotlin vs. java- what kotlin has that java does not
Go: It's Not Just For Google
オープンデータを使ったモバイルアプリ開発(応用編)
Modern technologies in data science
Implementing Software Machines in Go and C
Something about Golang

More from Colin Su (20)

PDF
Introduction to Google Compute Engine
PDF
Introduction to Google Cloud Endpoints: Speed Up Your API Development
PDF
Web2py Code Lab
PDF
A Tour of Google Cloud Platform
PDF
Introduction to Facebook JavaScript & Python SDK
PDF
Introduction to MapReduce & hadoop
PDF
Introduction to Google App Engine
PDF
Django Deployer
PDF
Introduction to Google - the most natural way to learn English (English Speech)
PDF
How to Speak Charms Like a Wizard
PDF
房地產報告
PDF
Introduction to Git
PDF
Introduction to Facebook Javascript SDK (NEW)
PDF
Introduction to Facebook Python API
PDF
Facebook Python SDK - Introduction
PDF
Web Programming - 1st TA Session
PDF
Nested List Comprehension and Binary Search
PDF
Python-List comprehension
PDF
Python-FileIO
KEY
Python Dictionary
Introduction to Google Compute Engine
Introduction to Google Cloud Endpoints: Speed Up Your API Development
Web2py Code Lab
A Tour of Google Cloud Platform
Introduction to Facebook JavaScript & Python SDK
Introduction to MapReduce & hadoop
Introduction to Google App Engine
Django Deployer
Introduction to Google - the most natural way to learn English (English Speech)
How to Speak Charms Like a Wizard
房地產報告
Introduction to Git
Introduction to Facebook Javascript SDK (NEW)
Introduction to Facebook Python API
Facebook Python SDK - Introduction
Web Programming - 1st TA Session
Nested List Comprehension and Binary Search
Python-List comprehension
Python-FileIO
Python Dictionary

Recently uploaded (20)

PDF
Electronic commerce courselecture one. Pdf
PPTX
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
PDF
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PPTX
A Presentation on Artificial Intelligence
PDF
NewMind AI Monthly Chronicles - July 2025
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PDF
CIFDAQ's Market Insight: SEC Turns Pro Crypto
PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
PDF
Modernizing your data center with Dell and AMD
PDF
Encapsulation theory and applications.pdf
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PPT
Teaching material agriculture food technology
PDF
Spectral efficient network and resource selection model in 5G networks
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PDF
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
Electronic commerce courselecture one. Pdf
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Agricultural_Statistics_at_a_Glance_2022_0.pdf
A Presentation on Artificial Intelligence
NewMind AI Monthly Chronicles - July 2025
“AI and Expert System Decision Support & Business Intelligence Systems”
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
Mobile App Security Testing_ A Comprehensive Guide.pdf
The Rise and Fall of 3GPP – Time for a Sabbatical?
CIFDAQ's Market Insight: SEC Turns Pro Crypto
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
Modernizing your data center with Dell and AMD
Encapsulation theory and applications.pdf
Chapter 3 Spatial Domain Image Processing.pdf
Teaching material agriculture food technology
Spectral efficient network and resource selection model in 5G networks
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...

Functional programming in Python