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 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

The joy of functional programming

  • 1.
  • 2.
    About Me • @CiaDteam in Scotiabank • I am Passionate about:  TDD, XP, Clean Code  Software craftsmanship  Learning, deliberate practice
  • 3.
    My Journey ToFunctional Programming
  • 4.
    The Joy ofFunctional Programming • Pure • Elegant • Powerful
  • 5.
    Anything that is “effectivelycomputable” can be computed by a Universal Turing Machine. - Alan Turing, 1936 Alan Turing
  • 6.
  • 7.
  • 8.
    Alonzo Church λ calculus Anythingthat is “effectively computable” can be computed by via λ Calculus. - Church 1933, 1935
  • 9.
    λ calculus • Inventedby mathematician Alonzo Church in the 1930s • It is anonymous function • Each lambda has single argument • Consists of a single transformation rule - variable substitution
  • 10.
  • 11.
    λ calculus isequivalent 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 • Purefunctions • Referential Transparency • Immutability • Declarative Programming
  • 15.
    Pure Functions • Camefrom 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 • Sameinput 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’tbe changed after it’s been created • No assignment • No shared state
  • 18.
    Declarative Programming • ImperativeProgramming - 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 voidquicksort(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
  • 21.
  • 22.
    Functional Programming Techniques • Highorder 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 thebuilding blocks  Standard  Self-contained  Independent  Easy to assemble
  • 32.
    Maybe Monad andNull References
  • 33.
    I call itmy billion-dollar mistake…. simply because it was so easy to implement. - Tony Hoare, null reference inventor Null References – A Billion-Dollar Mistake
  • 34.
  • 35.
    Imperative way public StringgetCarInsuranceName(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 OptionalAPI Optional.of(car) Optional.empty() Optional.ofNullable(car)
  • 37.
    Optional is aContainer
  • 38.
    The Functional Alternative publicString getCarInsuranceName(Optional<Person> person) { return person .flatMap(Person::getCar) .flatMap(Car::getInsurance) .map(Insurance::getName) .orElse("Unknown"); }
  • 39.
  • 41.
    The Problem ofOO 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, imperativeshell • 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.
  • 44.
    FP and SimpleDesign • 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 SOLIDPrinciples • 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 Unittests 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 DesignPatterns • 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 toClean Code we should master the Functional programming
  • 49.
  • 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 isHARD • A big mindset change – Imperative to Functional • Your past experiences won’t help – unlearn first • Be patient, it takes time Learn Unlearn Relearn
  • 52.
  • 53.
    FP books forJavaScript
  • 54.
  • 55.
    “One of ourdifficulties will be the maintenance of an appropriate discipline, so that we do not lose track of what we are doing.”
  • 56.
    • Take awaygoto 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.

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