@voiser
Introduction to FP
“Functional programming is a style of
programming which models computations as
the evaluation of expressions.”
https://www.haskell.org/haskellwiki/Functional_programming
imperative style vs functional style
recipes vs expressions
http://commons.wikimedia.org/wiki/File:Turnstile_state_machine_colored.svg
GUL UC3M - Introduction to functional programming
def sort(array):
less = []
equal = []
greater = []
if len(array) > 1:
pivot = array[0]
for x in array:
if x < pivot:
less.append(x)
if x == pivot:
equal.append(x)
if x > pivot:
greater.append(x)
return sort(less)+equal+sort(greater)
else:
return array
http://stackoverflow.com/questions/18262306/quick-sort-with-python
def qsort1(list):
if list == []:
return []
else:
pivot = list[0]
lesser = qsort1([x for x in list[1:] if x < pivot])
greater = qsort1([x for x in list[1:] if x >= pivot])
return lesser + [pivot] + greater
http://en.literateprograms.org/Quicksort_(Python)
“Many programming languages support
programming in both functional and imperative
style but the syntax and facilities of a language
are typically optimised for only one of these
styles, and social factors like coding
conventions and libraries often force the
programmer towards one of the styles.”
https://www.haskell.org/haskellwiki/Functional_programming
qsort [] = []
qsort (p:xs) = qsort1 lesser ++ [p] ++ qsort1 greater
where
lesser = [ y | y <- xs, y < p ]
greater = [ y | y <- xs, y >= p ]
http://en.literateprograms.org/Quicksort_(Haskell)
first class functions*
* Also available in your favourite imperative language
interface Filter<T> {
boolean filters(T t);
}
List<T> filter(List<T> original, Filter<T> filter) {
List<T> newList = new LinkedList<T>();
for (T elem : original) {
if (filter.filters(elem)) {
newList.add(elem);
}
}
return newList;
}
List<Integer> myList = …
filter(myList, new Filter<Integer>() {
boolean filters(Integer t) {
return t > 10;
}
});
filter f xs = [x | x <- xs, f x]
filter (x -> x > 10) myList
dealing with state, the functional way*
Response dispatch(Request req) {
if (config.blah()) {
if (config.bleh()) {
return dispatchCase1(req)
} else {
return dispatchCase2(req)
}
} else {
if (config.bleh()) {
return dispatchCase3(req)
} else {
return dispatchCase4(req)
}
}
}
Response dispatch(Request req) {
int case = config.getDispatchCase()
switch (case) {
case 1: return dispatchCase1(req)
case 2: return dispatchCase2(req)
case 3: return dispatchCase3(req)
case 4: return dispatchCase4(req)
}
}
// when more cases arrive, this code must be updated -> %&#$!!!
interface Dispatcher {
Response dispatch(Request);
}
Map[Configuration, Dispatcher] dispatchers = …
Response dispatch (Request req) {
dispatchers.get(config).dispatch(req)
}
Type Dispatcher = (Request => Response)
val dispatchers : Map[Configuration, Dispatcher] = ...
def dispatch (req : Request) = dispatchers.get(config)(req)
val dispatchers : Stack[Dispatcher] = ...
def dispatch(req : Request) = dispatchers.top()(req)
// some event arrives, starting a transitory state
val d : Dispatcher = { r : Request => ... }
dispatchers.push(d)
// the transitory state finishes, fall back to latest state
dispatchers.pull()
lazy evaluation*
def fibFrom(a: Int, b: Int): Stream[Int] = a #:: fibFrom(b, a + b)
val fibs = fibFrom(1, 1)
immutability*
* Language independent, but surprisingly, some languages encourage mutability.
class Person {
string name
int age;
boolean married;
// getters and setters
}
function getInfo(Person p) {
return p.getName()
+ “ is “
+ p.getAge()
+ “ years old and is “
+ (p.isMarried()? “married” : “not married”)
}
function update(Person p, int age, married m) {
p.setAge(age);
p.setMarried(m);
}
class Person {
final string name;
final int age;
final boolean married;
}
function getInfo(Person p) {
return p.name
+ “ is ”
+ p.age
+ “ years old and is “
+ (p.married? “married” : “not married”)
}
function update(Person p, int age, married m) {
return new Person(p.name, age, married)
}
avoid mutability with (tail) recursion*
square [] = []
square (x:xs) = x * x : square xs
Q: Is FP perfect for everything?
A: No.
Q: Should I learn a new language?
A: No. You can start adopting functional
patterns in your current favourite language.
Q: What if I want to learn a new language?
A: Well, my personal recommendation is...
gul.es
@guluc3m

More Related Content

PDF
T3chFest 2016 - The polyglot programmer
PDF
The best language in the world
PPTX
Python
PDF
Quark: A Purely-Functional Scala DSL for Data Processing & Analytics
PDF
Functional Algebra: Monoids Applied
PPTX
Lambda выражения и Java 8
PDF
The Easy-Peasy-Lemon-Squeezy, Statically-Typed, Purely Functional Programming...
PDF
MTL Versus Free
T3chFest 2016 - The polyglot programmer
The best language in the world
Python
Quark: A Purely-Functional Scala DSL for Data Processing & Analytics
Functional Algebra: Monoids Applied
Lambda выражения и Java 8
The Easy-Peasy-Lemon-Squeezy, Statically-Typed, Purely Functional Programming...
MTL Versus Free

What's hot (20)

PDF
The Death of Final Tagless
PDF
Java Class Design
PDF
Pune Clojure Course Outline
PDF
"Немного о функциональном программирование в JavaScript" Алексей Коваленко
PDF
Halogen: Past, Present, and Future
PDF
The Design of the Scalaz 8 Effect System
ODP
JavaScript Web Development
PDF
Why Haskell
PDF
RESTful API using scalaz (3)
PDF
Demystifying functional programming with Scala
PPTX
Scala - where objects and functions meet
PDF
Pragmatic Real-World Scala (short version)
PDF
Scalaz By Example (An IO Taster) -- PDXScala Meetup Jan 2014
PDF
Post-Free: Life After Free Monads
PPT
Stack queue
PDF
ES6 - Next Generation Javascript
PPT
Initial Java Core Concept
PDF
Advanced Tagless Final - Saying Farewell to Free
PPTX
Intro to Functional Programming in Scala
PPTX
Introduction to Monads in Scala (1)
The Death of Final Tagless
Java Class Design
Pune Clojure Course Outline
"Немного о функциональном программирование в JavaScript" Алексей Коваленко
Halogen: Past, Present, and Future
The Design of the Scalaz 8 Effect System
JavaScript Web Development
Why Haskell
RESTful API using scalaz (3)
Demystifying functional programming with Scala
Scala - where objects and functions meet
Pragmatic Real-World Scala (short version)
Scalaz By Example (An IO Taster) -- PDXScala Meetup Jan 2014
Post-Free: Life After Free Monads
Stack queue
ES6 - Next Generation Javascript
Initial Java Core Concept
Advanced Tagless Final - Saying Farewell to Free
Intro to Functional Programming in Scala
Introduction to Monads in Scala (1)
Ad

Similar to GUL UC3M - Introduction to functional programming (20)

PDF
Spark workshop
PDF
TI1220 Lecture 8: Traits & Type Parameterization
PDF
Monadologie
PDF
TI1220 Lecture 6: First-class Functions
PDF
From Java to Scala - advantages and possible risks
PDF
Introduction to Scala
PDF
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
PDF
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
PDF
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
PDF
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
PDF
Lecture 5: Functional Programming
PPTX
Big Data Day LA 2016/ Hadoop/ Spark/ Kafka track - Iterative Spark Developmen...
PDF
(How) can we benefit from adopting scala?
PDF
2013 28-03-dak-why-fp
PDF
Scala by Luc Duponcheel
PDF
Lecture 3
PDF
Practical cats
PDF
Functional programming ii
PPT
SDC - Einführung in Scala
PPTX
SF Scala meet up, lighting talk: SPA -- Scala JDBC wrapper
Spark workshop
TI1220 Lecture 8: Traits & Type Parameterization
Monadologie
TI1220 Lecture 6: First-class Functions
From Java to Scala - advantages and possible risks
Introduction to Scala
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
Lecture 5: Functional Programming
Big Data Day LA 2016/ Hadoop/ Spark/ Kafka track - Iterative Spark Developmen...
(How) can we benefit from adopting scala?
2013 28-03-dak-why-fp
Scala by Luc Duponcheel
Lecture 3
Practical cats
Functional programming ii
SDC - Einführung in Scala
SF Scala meet up, lighting talk: SPA -- Scala JDBC wrapper
Ad

Recently uploaded (20)

PPT
3.Software Design for software engineering
PPTX
WJQSJXNAZJVCVSAXJHBZKSJXKJKXJSBHJBJEHHJB
PPTX
Folder Lock 10.1.9 Crack With Serial Key
PPTX
Streamlining Project Management in the AV Industry with D-Tools for Zoho CRM ...
PDF
MiniTool Power Data Recovery 12.6 Crack + Portable (Latest Version 2025)
PPTX
DevOpsDays Halifax 2025 - Building 10x Organizations Using Modern Productivit...
PDF
MAGIX Sound Forge Pro CrackSerial Key Keygen
PPTX
DevOpsDays Halifax 2025 - Building 10x Organizations Using Modern Productivit...
PPTX
Human Computer Interaction lecture Chapter 2.pptx
PDF
CapCut PRO for PC Crack New Download (Fully Activated 2025)
PPTX
string python Python Strings: Literals, Slicing, Methods, Formatting, and Pra...
PDF
IT Consulting Services to Secure Future Growth
PPTX
Bandicam Screen Recorder 8.2.1 Build 2529 Crack
PDF
Building an Inclusive Web Accessibility Made Simple with Accessibility Analyzer
PPTX
ROI from Efficient Content & Campaign Management in the Digital Media Industry
PDF
PDF-XChange Editor Plus 10.7.0.398.0 Crack Free Download Latest 2025
PDF
Mobile App Backend Development with WordPress REST API: The Complete eBook
PDF
IDM Crack 6.42 Build 42 Patch Serial Key 2025 Free New Version
PPTX
Plex Media Server 1.28.2.6151 With Crac5 2022 Free .
PDF
Internet Download Manager IDM Crack powerful download accelerator New Version...
3.Software Design for software engineering
WJQSJXNAZJVCVSAXJHBZKSJXKJKXJSBHJBJEHHJB
Folder Lock 10.1.9 Crack With Serial Key
Streamlining Project Management in the AV Industry with D-Tools for Zoho CRM ...
MiniTool Power Data Recovery 12.6 Crack + Portable (Latest Version 2025)
DevOpsDays Halifax 2025 - Building 10x Organizations Using Modern Productivit...
MAGIX Sound Forge Pro CrackSerial Key Keygen
DevOpsDays Halifax 2025 - Building 10x Organizations Using Modern Productivit...
Human Computer Interaction lecture Chapter 2.pptx
CapCut PRO for PC Crack New Download (Fully Activated 2025)
string python Python Strings: Literals, Slicing, Methods, Formatting, and Pra...
IT Consulting Services to Secure Future Growth
Bandicam Screen Recorder 8.2.1 Build 2529 Crack
Building an Inclusive Web Accessibility Made Simple with Accessibility Analyzer
ROI from Efficient Content & Campaign Management in the Digital Media Industry
PDF-XChange Editor Plus 10.7.0.398.0 Crack Free Download Latest 2025
Mobile App Backend Development with WordPress REST API: The Complete eBook
IDM Crack 6.42 Build 42 Patch Serial Key 2025 Free New Version
Plex Media Server 1.28.2.6151 With Crac5 2022 Free .
Internet Download Manager IDM Crack powerful download accelerator New Version...

GUL UC3M - Introduction to functional programming

  • 2. “Functional programming is a style of programming which models computations as the evaluation of expressions.” https://www.haskell.org/haskellwiki/Functional_programming
  • 3. imperative style vs functional style
  • 7. def sort(array): less = [] equal = [] greater = [] if len(array) > 1: pivot = array[0] for x in array: if x < pivot: less.append(x) if x == pivot: equal.append(x) if x > pivot: greater.append(x) return sort(less)+equal+sort(greater) else: return array http://stackoverflow.com/questions/18262306/quick-sort-with-python
  • 8. def qsort1(list): if list == []: return [] else: pivot = list[0] lesser = qsort1([x for x in list[1:] if x < pivot]) greater = qsort1([x for x in list[1:] if x >= pivot]) return lesser + [pivot] + greater http://en.literateprograms.org/Quicksort_(Python)
  • 9. “Many programming languages support programming in both functional and imperative style but the syntax and facilities of a language are typically optimised for only one of these styles, and social factors like coding conventions and libraries often force the programmer towards one of the styles.” https://www.haskell.org/haskellwiki/Functional_programming
  • 10. qsort [] = [] qsort (p:xs) = qsort1 lesser ++ [p] ++ qsort1 greater where lesser = [ y | y <- xs, y < p ] greater = [ y | y <- xs, y >= p ] http://en.literateprograms.org/Quicksort_(Haskell)
  • 11. first class functions* * Also available in your favourite imperative language
  • 12. interface Filter<T> { boolean filters(T t); } List<T> filter(List<T> original, Filter<T> filter) { List<T> newList = new LinkedList<T>(); for (T elem : original) { if (filter.filters(elem)) { newList.add(elem); } } return newList; }
  • 13. List<Integer> myList = … filter(myList, new Filter<Integer>() { boolean filters(Integer t) { return t > 10; } });
  • 14. filter f xs = [x | x <- xs, f x]
  • 15. filter (x -> x > 10) myList
  • 16. dealing with state, the functional way*
  • 17. Response dispatch(Request req) { if (config.blah()) { if (config.bleh()) { return dispatchCase1(req) } else { return dispatchCase2(req) } } else { if (config.bleh()) { return dispatchCase3(req) } else { return dispatchCase4(req) } } }
  • 18. Response dispatch(Request req) { int case = config.getDispatchCase() switch (case) { case 1: return dispatchCase1(req) case 2: return dispatchCase2(req) case 3: return dispatchCase3(req) case 4: return dispatchCase4(req) } } // when more cases arrive, this code must be updated -> %&#$!!!
  • 19. interface Dispatcher { Response dispatch(Request); } Map[Configuration, Dispatcher] dispatchers = … Response dispatch (Request req) { dispatchers.get(config).dispatch(req) }
  • 20. Type Dispatcher = (Request => Response) val dispatchers : Map[Configuration, Dispatcher] = ... def dispatch (req : Request) = dispatchers.get(config)(req)
  • 21. val dispatchers : Stack[Dispatcher] = ... def dispatch(req : Request) = dispatchers.top()(req) // some event arrives, starting a transitory state val d : Dispatcher = { r : Request => ... } dispatchers.push(d) // the transitory state finishes, fall back to latest state dispatchers.pull()
  • 23. def fibFrom(a: Int, b: Int): Stream[Int] = a #:: fibFrom(b, a + b) val fibs = fibFrom(1, 1)
  • 24. immutability* * Language independent, but surprisingly, some languages encourage mutability.
  • 25. class Person { string name int age; boolean married; // getters and setters } function getInfo(Person p) { return p.getName() + “ is “ + p.getAge() + “ years old and is “ + (p.isMarried()? “married” : “not married”) } function update(Person p, int age, married m) { p.setAge(age); p.setMarried(m); }
  • 26. class Person { final string name; final int age; final boolean married; } function getInfo(Person p) { return p.name + “ is ” + p.age + “ years old and is “ + (p.married? “married” : “not married”) } function update(Person p, int age, married m) { return new Person(p.name, age, married) }
  • 27. avoid mutability with (tail) recursion*
  • 28. square [] = [] square (x:xs) = x * x : square xs
  • 29. Q: Is FP perfect for everything? A: No.
  • 30. Q: Should I learn a new language? A: No. You can start adopting functional patterns in your current favourite language.
  • 31. Q: What if I want to learn a new language? A: Well, my personal recommendation is...