SlideShare a Scribd company logo
The Joy Of
Functional
Programming
Steve Zhang
About Me
• @CiaD team in Scotiabank
• I am Passionate about:
 TDD, XP, Clean Code
 Software craftsmanship
 Learning, deliberate practice
My Journey To Functional
Programming
The Joy of Functional
Programming
• Pure
• Elegant
• Powerful
Anything that is
“effectively computable”
can be computed by a
Universal Turing
Machine.
- Alan Turing, 1936
Alan Turing
History
Universal Turing Machine
Alonzo Church
λ calculus
Anything that is
“effectively computable”
can be computed by via
λ Calculus.
- Church 1933, 1935
λ calculus
• Invented by mathematician Alonzo Church
in the 1930s
• It is anonymous function
• Each lambda has single argument
• Consists of a single transformation rule -
variable substitution
λ calculus
𝜆𝑥.𝑥
Head
Body
(Expression)
Argument
λ calculus is equivalent to Turing
machines
Turing machine Lambda Calculus
Imperative Programming Functional Programming
 Assembly
 C / C++
 Java
 JavaScript
 OO …
 Lisp
 Erlang
 Haskell
 Scala
 F# ….
Lambda Calculus influences
• Lisp (lambda (x) (* x x))
• Ruby lambda { |name| "Hi #{name}!" }
• Java 8 isOdd = n -> n % 2 != 0;
• JS var multiply = (x, y) => { return x * y
};
• Haskell addOne = x -> x + 1
What is Functional
Programming
• A Programming paradigm based on
functions
• Function is a first class citizen
- can be a variable
- passed as argument
- return as a value
• Roots in Lambda calculus
Functional Programming
Concepts
• Pure functions
• Referential Transparency
• Immutability
• Declarative Programming
Pure Functions
• Came from Math functions, a function is
a mapping between input and output
• Output value only depends on input
value
• No external dependencies
• Will not update any global state
x ↦ f (x)
Referential Transparency
• Same input always get the same result
• Every subexpression can be substituted
by any other that’s equal to it in value
• Easier to reason
• RT functions will NOT
- print on screen
- output logs
Immutability
• Data can’t be changed after it’s been
created
• No assignment
• No shared state
Declarative Programming
• Imperative Programming
- uses statements that change a
program's state
- Focus on how a program operate
• Declarative Programming
- expresses the logic of a computation
without describing its control flow
- Focus on what a program achieve
Quicksort In C
void quicksort(int *A, int len) {
if (len < 2) return;
int pivot = A[len / 2];
int i, j;
for (i = 0, j = len - 1; ; i++, j--) {
while (A[i] < pivot) i++;
while (A[j] > pivot) j--;
if (i >= j) break;
int temp = A[i];
A[i] = A[j];
A[j] = temp;
}
quicksort(A, i);
quicksort(A + i, len - i);
}
Quicksort in Haskell
quicksort :: Ord a => [a] -> [a]
quicksort [] = []
quicksort (p:xs) = (quicksort lesser) ++ [p] ++ (quicksort greater)
where
lesser = filter (< p) xs
greater = filter (>= p) xs
FP techniques
Functional Programming
Techniques
• High order function
• Recursion
• Composition
• Lazy Evaluation
• Currying
• Pattern matching
• Algebraic type
• Functor
• Applicative
• Monoid
• Monad
High Order Functions
• Function that takes another function as
argument
• Return function as a result
- Map
- Filter
- Fold (Reduce)
Map
map (x -> x*x) [1, 2, 3, 4, 5]
[1, 4, 9, 16, 25]
map _ [] = []
map f (x : xs) = f x : map f xs
Filter
filter even [1..10]  [2,4,6,8,10]
filter _ [] = []
filter p (x:xs)
| p x = x : filter p xs
| otherwise = filter p xs
Fold (Reduce)
• sum [1, 5, 10]  16
• product [2,3,4]  24
sum [] = 0
sum (x:xs) = x + sum xs
product [] = 1
product (x:xs) = x * product xs
concat [] = []
concat (x:xs) = x ++ concat xs
Identify the
similar structure,
abstract the
common pattern
foldr
foldr f z [] = z
foldr f z (x:xs) = f x (foldr f z xs)
sum = foldr (+) 0
product = foldr (*) 1
concat = foldr (++) []
Conclusion
Map / Filter / Reduce can replace almost all
the loops
Function composition
(f . g) x = f (g x)
( sum . take 5 . filter even ) [1..100]
ls -l | grep key | less
functions are Lego bricks, they are easily
assembled
Functions are the building
blocks
 Standard
 Self-contained
 Independent
 Easy to assemble
Maybe Monad and Null
References
I call it my billion-dollar
mistake…. simply
because it was so easy
to implement.
- Tony Hoare, null
reference inventor
Null References – A Billion-Dollar
Mistake
Java Example
Imperative way
public String getCarInsuranceName(Person person)
{
if (person != null) {
Car car = person.getCar();
if (car != null) {
Insurance insurance = car.getInsurance();
if (insurance != null) {
return insurance.getName();
}
}
}
return "Unknown";
}
Java 8 Optional API
Optional.of(car) Optional.empty()
Optional.ofNullable(car)
Optional is a Container
The Functional Alternative
public String
getCarInsuranceName(Optional<Person> person) {
return person
.flatMap(Person::getCar)
.flatMap(Car::getInsurance)
.map(Insurance::getName)
.orElse("Unknown");
}
FP and OO
The joy of functional programming
The Problem of OO
The problem with object-oriented
languages is they’ve got all this implicit
environment that they carry around with
them. You wanted a banana but what
you got was a gorilla holding the
banana... and the entire jungle.
- Joe Armstrong
Functional core, imperative shell
• Core – FP pure
functions, business
logic
• Shell – OO
• Separation of
concerns
https://www.destroyallsoftware.com/talks/boundarie
s
http://www.mokacoding.com/blog/functional-core-reactive-shell/
FP and Clean Code
FP and Simple Design
• Functional Programming leads to simple
design
• Function depends only on input, no
external dependencies
• Reduce complexity
• Easy to compose
• Easy to reason
FP and SOLID Principles
• SRP – each pure function has single
responsibility
• OCP - logics are easy to extend via
Function composition, easy to integrate,
no glue code
• DIP - functions are injected into high
order functions
• LSP - pure functions are substitutable
• ISP - …
FP makes Unit tests easy
Michael Feathers’ Unit Test definition:
Should NOT access the file system
Should NOT access a database
Should NOT access any network
resources
Should NOT depend on local configuration
Pure functions meet these requirements
naturally
FP and Design Patterns
• Many design patterns are absorbed into
functional programming paradigm:
- template method
- strategy
- chains of responsibility
- decorator
- command
- visitor pattern  Functor and Monad
Conclusion
Functional Programming leads
to Clean Code
we should master the
Functional programming
Two approaches, same
Destination
FP learning path
• Start from where you are, begin with
lambda
- Java 8
- JavaScript ES 6
- Scala
• Learn an new FP language, unlearn your
past experiences
- Haskell
Learning FP is HARD
• A big mindset change – Imperative to
Functional
• Your past experiences won’t help –
unlearn first
• Be patient, it takes time
Learn Unlearn Relearn
Recommended books
FP books for JavaScript
Review The History Again
“One of our difficulties will
be the maintenance of an
appropriate discipline, so
that we do not lose track
of what we are doing.”
• Take away goto
statements
Structure
Programming
• Take away pointersObject
Oriented
• Take away assignmentsFunctional
Programming
Some Final Thoughts
• Functional Programming brings more
disciplines to programming
• Since Functional Programming is rooted in
math, it will change programming from
craft to science.
• Function Programming will take software
craftsmanship movement to the next level
Q&A

More Related Content

PDF
Functional programming in scala
PPTX
Functional programming and ruby in functional style
KEY
Scala: functional programming for the imperative mind
PPTX
Can programming be liberated from the von neumann style?
PPTX
05 functional programming
PPT
Lisp Programming Languge
PPTX
PDF
Gentle Introduction To Lisp
Functional programming in scala
Functional programming and ruby in functional style
Scala: functional programming for the imperative mind
Can programming be liberated from the von neumann style?
05 functional programming
Lisp Programming Languge
Gentle Introduction To Lisp

What's hot (20)

PDF
Functional Go
PPTX
The Road to Lambda - Mike Duigou
ODP
From Perl To Elixir
PDF
使用.NET构建轻量级分布式框架
PPTX
To Lombok or not to Lombok | J-Fall 2019
ODP
Elixir basics-2
PPTX
PPTX
Functional programming for the Advanced Beginner
ODP
Elixir basics
PPTX
What`s New in Java 8
PDF
Functional Programming in Scala
PDF
Intro to JavaScript - Week 2: Function
PPTX
Practical Malware Analysis: Ch 6: Recognizing C Code Constructs in Assembly
PPT
Functional Programming Past Present Future
PDF
Introduction to kotlin
PDF
CNIT 126 6: Recognizing C Code Constructs in Assembly
PPT
KEY
Scala clojure techday_2011
PPTX
Introduction to Scala language
PPTX
20170714 concurrency in julia
Functional Go
The Road to Lambda - Mike Duigou
From Perl To Elixir
使用.NET构建轻量级分布式框架
To Lombok or not to Lombok | J-Fall 2019
Elixir basics-2
Functional programming for the Advanced Beginner
Elixir basics
What`s New in Java 8
Functional Programming in Scala
Intro to JavaScript - Week 2: Function
Practical Malware Analysis: Ch 6: Recognizing C Code Constructs in Assembly
Functional Programming Past Present Future
Introduction to kotlin
CNIT 126 6: Recognizing C Code Constructs in Assembly
Scala clojure techday_2011
Introduction to Scala language
20170714 concurrency in julia
Ad

Similar to The joy of functional programming (20)

PDF
Introduction to functional programming (In Arabic)
PDF
Functional programming is the most extreme programming
PDF
Why you should care about functional programming
PDF
Functional Programming for Busy Object Oriented Programmers
PDF
Introduction to functional programming
PPT
Functional Programming - Past, Present and Future
PDF
Functional Programming #FTW
PPTX
Good functional programming is good programming
PPS
Presentation of GetTogether on Functional Programming
PPTX
Introduction to Functional Programming
PDF
A (very brief) into to Functional Programming
PDF
A taste of Functional Programming
PDF
Functional programming in Scala
PDF
Fp for the oo programmer
PDF
Go Beyond Higher Order Functions: A Journey into Functional Programming
PPTX
Functional pogramming hl overview
PDF
OOP and FP
PPTX
Functional Programming Concepts for Imperative Programmers
PPTX
Why functional programming in C# & F#
PPTX
Functional programming
Introduction to functional programming (In Arabic)
Functional programming is the most extreme programming
Why you should care about functional programming
Functional Programming for Busy Object Oriented Programmers
Introduction to functional programming
Functional Programming - Past, Present and Future
Functional Programming #FTW
Good functional programming is good programming
Presentation of GetTogether on Functional Programming
Introduction to Functional Programming
A (very brief) into to Functional Programming
A taste of Functional Programming
Functional programming in Scala
Fp for the oo programmer
Go Beyond Higher Order Functions: A Journey into Functional Programming
Functional pogramming hl overview
OOP and FP
Functional Programming Concepts for Imperative Programmers
Why functional programming in C# & F#
Functional programming
Ad

Recently uploaded (20)

PPTX
Sustainable Sites - Green Building Construction
PPTX
CYBER-CRIMES AND SECURITY A guide to understanding
PPT
CRASH COURSE IN ALTERNATIVE PLUMBING CLASS
PPT
Project quality management in manufacturing
PPTX
CH1 Production IntroductoryConcepts.pptx
PPTX
MET 305 2019 SCHEME MODULE 2 COMPLETE.pptx
DOCX
ASol_English-Language-Literature-Set-1-27-02-2023-converted.docx
PPTX
KTU 2019 -S7-MCN 401 MODULE 2-VINAY.pptx
PPTX
Recipes for Real Time Voice AI WebRTC, SLMs and Open Source Software.pptx
PDF
SM_6th-Sem__Cse_Internet-of-Things.pdf IOT
PPTX
Infosys Presentation by1.Riyan Bagwan 2.Samadhan Naiknavare 3.Gaurav Shinde 4...
PDF
Evaluating the Democratization of the Turkish Armed Forces from a Normative P...
PDF
Automation-in-Manufacturing-Chapter-Introduction.pdf
PPTX
CARTOGRAPHY AND GEOINFORMATION VISUALIZATION chapter1 NPTE (2).pptx
PDF
Operating System & Kernel Study Guide-1 - converted.pdf
PDF
TFEC-4-2020-Design-Guide-for-Timber-Roof-Trusses.pdf
PPTX
Welding lecture in detail for understanding
PPTX
Engineering Ethics, Safety and Environment [Autosaved] (1).pptx
PPTX
Foundation to blockchain - A guide to Blockchain Tech
DOCX
573137875-Attendance-Management-System-original
Sustainable Sites - Green Building Construction
CYBER-CRIMES AND SECURITY A guide to understanding
CRASH COURSE IN ALTERNATIVE PLUMBING CLASS
Project quality management in manufacturing
CH1 Production IntroductoryConcepts.pptx
MET 305 2019 SCHEME MODULE 2 COMPLETE.pptx
ASol_English-Language-Literature-Set-1-27-02-2023-converted.docx
KTU 2019 -S7-MCN 401 MODULE 2-VINAY.pptx
Recipes for Real Time Voice AI WebRTC, SLMs and Open Source Software.pptx
SM_6th-Sem__Cse_Internet-of-Things.pdf IOT
Infosys Presentation by1.Riyan Bagwan 2.Samadhan Naiknavare 3.Gaurav Shinde 4...
Evaluating the Democratization of the Turkish Armed Forces from a Normative P...
Automation-in-Manufacturing-Chapter-Introduction.pdf
CARTOGRAPHY AND GEOINFORMATION VISUALIZATION chapter1 NPTE (2).pptx
Operating System & Kernel Study Guide-1 - converted.pdf
TFEC-4-2020-Design-Guide-for-Timber-Roof-Trusses.pdf
Welding lecture in detail for understanding
Engineering Ethics, Safety and Environment [Autosaved] (1).pptx
Foundation to blockchain - A guide to Blockchain Tech
573137875-Attendance-Management-System-original

The joy of functional programming

  • 2. About Me • @CiaD team in Scotiabank • I am Passionate about:  TDD, XP, Clean Code  Software craftsmanship  Learning, deliberate practice
  • 3. My Journey To Functional Programming
  • 4. The Joy of Functional Programming • Pure • Elegant • Powerful
  • 5. Anything that is “effectively computable” can be computed by a Universal Turing Machine. - Alan Turing, 1936 Alan Turing
  • 8. Alonzo Church λ calculus Anything that is “effectively computable” can be computed by via λ Calculus. - Church 1933, 1935
  • 9. λ calculus • Invented by mathematician Alonzo Church in the 1930s • It is anonymous function • Each lambda has single argument • Consists of a single transformation rule - variable substitution
  • 11. λ calculus is equivalent to Turing machines Turing machine Lambda Calculus Imperative Programming Functional Programming  Assembly  C / C++  Java  JavaScript  OO …  Lisp  Erlang  Haskell  Scala  F# ….
  • 12. Lambda Calculus influences • Lisp (lambda (x) (* x x)) • Ruby lambda { |name| "Hi #{name}!" } • Java 8 isOdd = n -> n % 2 != 0; • JS var multiply = (x, y) => { return x * y }; • Haskell addOne = x -> x + 1
  • 13. What is Functional Programming • A Programming paradigm based on functions • Function is a first class citizen - can be a variable - passed as argument - return as a value • Roots in Lambda calculus
  • 14. Functional Programming Concepts • Pure functions • Referential Transparency • Immutability • Declarative Programming
  • 15. Pure Functions • Came from Math functions, a function is a mapping between input and output • Output value only depends on input value • No external dependencies • Will not update any global state x ↦ f (x)
  • 16. Referential Transparency • Same input always get the same result • Every subexpression can be substituted by any other that’s equal to it in value • Easier to reason • RT functions will NOT - print on screen - output logs
  • 17. Immutability • Data can’t be changed after it’s been created • No assignment • No shared state
  • 18. Declarative Programming • Imperative Programming - uses statements that change a program's state - Focus on how a program operate • Declarative Programming - expresses the logic of a computation without describing its control flow - Focus on what a program achieve
  • 19. Quicksort In C void quicksort(int *A, int len) { if (len < 2) return; int pivot = A[len / 2]; int i, j; for (i = 0, j = len - 1; ; i++, j--) { while (A[i] < pivot) i++; while (A[j] > pivot) j--; if (i >= j) break; int temp = A[i]; A[i] = A[j]; A[j] = temp; } quicksort(A, i); quicksort(A + i, len - i); }
  • 20. Quicksort in Haskell quicksort :: Ord a => [a] -> [a] quicksort [] = [] quicksort (p:xs) = (quicksort lesser) ++ [p] ++ (quicksort greater) where lesser = filter (< p) xs greater = filter (>= p) xs
  • 22. Functional Programming Techniques • High order function • Recursion • Composition • Lazy Evaluation • Currying • Pattern matching • Algebraic type • Functor • Applicative • Monoid • Monad
  • 23. High Order Functions • Function that takes another function as argument • Return function as a result - Map - Filter - Fold (Reduce)
  • 24. Map map (x -> x*x) [1, 2, 3, 4, 5] [1, 4, 9, 16, 25] map _ [] = [] map f (x : xs) = f x : map f xs
  • 25. Filter filter even [1..10]  [2,4,6,8,10] filter _ [] = [] filter p (x:xs) | p x = x : filter p xs | otherwise = filter p xs
  • 26. Fold (Reduce) • sum [1, 5, 10]  16 • product [2,3,4]  24
  • 27. sum [] = 0 sum (x:xs) = x + sum xs product [] = 1 product (x:xs) = x * product xs concat [] = [] concat (x:xs) = x ++ concat xs Identify the similar structure, abstract the common pattern
  • 28. foldr foldr f z [] = z foldr f z (x:xs) = f x (foldr f z xs) sum = foldr (+) 0 product = foldr (*) 1 concat = foldr (++) []
  • 29. Conclusion Map / Filter / Reduce can replace almost all the loops
  • 30. Function composition (f . g) x = f (g x) ( sum . take 5 . filter even ) [1..100] ls -l | grep key | less functions are Lego bricks, they are easily assembled
  • 31. Functions are the building blocks  Standard  Self-contained  Independent  Easy to assemble
  • 32. Maybe Monad and Null References
  • 33. I call it my billion-dollar mistake…. simply because it was so easy to implement. - Tony Hoare, null reference inventor Null References – A Billion-Dollar Mistake
  • 35. Imperative way public String getCarInsuranceName(Person person) { if (person != null) { Car car = person.getCar(); if (car != null) { Insurance insurance = car.getInsurance(); if (insurance != null) { return insurance.getName(); } } } return "Unknown"; }
  • 36. Java 8 Optional API Optional.of(car) Optional.empty() Optional.ofNullable(car)
  • 37. Optional is a Container
  • 38. The Functional Alternative public String getCarInsuranceName(Optional<Person> person) { return person .flatMap(Person::getCar) .flatMap(Car::getInsurance) .map(Insurance::getName) .orElse("Unknown"); }
  • 41. The Problem of OO The problem with object-oriented languages is they’ve got all this implicit environment that they carry around with them. You wanted a banana but what you got was a gorilla holding the banana... and the entire jungle. - Joe Armstrong
  • 42. Functional core, imperative shell • Core – FP pure functions, business logic • Shell – OO • Separation of concerns https://www.destroyallsoftware.com/talks/boundarie s http://www.mokacoding.com/blog/functional-core-reactive-shell/
  • 43. FP and Clean Code
  • 44. FP and Simple Design • Functional Programming leads to simple design • Function depends only on input, no external dependencies • Reduce complexity • Easy to compose • Easy to reason
  • 45. FP and SOLID Principles • SRP – each pure function has single responsibility • OCP - logics are easy to extend via Function composition, easy to integrate, no glue code • DIP - functions are injected into high order functions • LSP - pure functions are substitutable • ISP - …
  • 46. FP makes Unit tests easy Michael Feathers’ Unit Test definition: Should NOT access the file system Should NOT access a database Should NOT access any network resources Should NOT depend on local configuration Pure functions meet these requirements naturally
  • 47. FP and Design Patterns • Many design patterns are absorbed into functional programming paradigm: - template method - strategy - chains of responsibility - decorator - command - visitor pattern  Functor and Monad
  • 48. Conclusion Functional Programming leads to Clean Code we should master the Functional programming
  • 50. FP learning path • Start from where you are, begin with lambda - Java 8 - JavaScript ES 6 - Scala • Learn an new FP language, unlearn your past experiences - Haskell
  • 51. Learning FP is HARD • A big mindset change – Imperative to Functional • Your past experiences won’t help – unlearn first • Be patient, it takes time Learn Unlearn Relearn
  • 53. FP books for JavaScript
  • 55. “One of our difficulties will be the maintenance of an appropriate discipline, so that we do not lose track of what we are doing.”
  • 56. • Take away goto statements Structure Programming • Take away pointersObject Oriented • Take away assignmentsFunctional Programming
  • 57. Some Final Thoughts • Functional Programming brings more disciplines to programming • Since Functional Programming is rooted in math, it will change programming from craft to science. • Function Programming will take software craftsmanship movement to the next level
  • 58. Q&A

Editor's Notes

  • #42: Encapsulation – hide state State mutation and state sharing Mixed data and behavior Hard to manage dependency Hard to compose and decompose