SlideShare a Scribd company logo
1 of 38
Download to read offline
FUNCTIONAL PROGRAMMING
INTRODUCTION TO
INTRODUCTION
CHAPTER 1
CHAPTER 1: INTRODUCTION
PROGRAMMING PARADIGMS
CHAPTER 1: INTRODUCTION
USAGE IN INDUSTRY
Haskell is the most famous functional language. It is being many big
companies like Facebook, Microsoft, AT&T as internal tools
Erlang / Elixir is the first-class choice for concurrency because of its Actor
Model. It’s most used in telecom industry and chat services (Facebook,
Whatsapp, Discord, Heroku, RabbitMQ, …)
Clojure belongs to LISP family and runs on JVM. It’s being used by CircleCI,
SoundCloud, Groupon, Weebly, , Netflix. Clojure is good for concurrency
with concepts like Persistent Data Structure and Software Transational
Memory
Scala is the solid choice for those who seek comfort in both Functional and
Object Oriented. It’s in use by big companies like: Twitter, Foursquare,
Soundcloud, 9GAG, Tumblr,…
PURITY
CHAPTER 2
CHAPTER 2: PURITY
Functional Languages favors “pure function”
A pure function is a function that:
- Output only depends on Input
- Has no side effects
CHAPTER 2: PURITY
examples of
pure functions:
function sayHello(name) {
return "Hello " + name;
}
var name = "Lam";
function sayHello() {
return "Hello " + name;
}
function sayHello() {
return "Hello " + this.name;
}
examples of
impure functions:
CHAPTER 2: PURITY
why pure functions matter
Pure function is deterministic, it always returns the same output for the
same input
It’s easy to understand and easy to test
Pure functions can be cached, impure functions cannot
FIRST-CLASS
FUNCTIONS
CHAPTER 3
CHAPTER 3: FIRST-CLASS FUNCTIONS
In Functional Languages, we don't strictly follow S-V-O
OOP
Subject.Verb (Object)
alice.SaysHelloTo("Bob")
Functional
Verb (Subject, Object)
SaysHelloTo(alice, ”Bob”)
CHAPTER 3: FIRST-CLASS FUNCTIONS
In Functional Languages, functions are first-class
- It can be assigned to a variable
- It can be passed into other function
- We can return a function from another function
First-class means that, functions plays an equal role as objects:
CHAPTER 3: FIRST-CLASS FUNCTIONS
Functions as objects
<?php
$foo = function() {
return "Hello World";
};
$foo(); // 'Hello world’
call_user_func($foo); // 'Hello world’
const hello = () => 'Hello World';
const foo = hello;
const bar = foo;
bar(); // 'Hello world’
bar.call(); // 'Hello world’
bar.length; // 1
Available in most programming languages
CHAPTER 3: FIRST-CLASS FUNCTIONS
Returning a function from a function
function add(number1) {
return function(number2) {
return number1 + number2;
}
}
add(3)(5) // 8
// instead of add(3, 5)
This is called Curry-ing, which is named after Haskell Curry
It helps you to build up function and gives name to those functions
var increment = add(1);
// . . .
// meanwhile, in another code
increment(2) // 3
CHAPTER 3: FIRST-CLASS FUNCTIONS
Passing function to another function
const whatToDoToday = (what) => {
return 'I am ' + what() // ‘I am doing TedTalk'
};
const action = random() > 0.5
? () => 'doing TedTalk'
: () => 'doing Nothing';
whatToDoToday(action);
In Javascript, function can be passed into other functions.
CHAPTER 3: FIRST-CLASS FUNCTIONS
First-Class Function is so powerful that in most Functional Languages, GoF
Design Patterns do not exist
COMPOSITION
CHAPTER 4
CHAPTER 4: COMPOSITION
Function Composition
(Cow) =>getMilk = Milk
(Milk) =>getCheese = Cheese
(Cheese) =>getPizza = Pizza
const getCheeseFromCow =
getMilk |> getCheese
CHAPTER 4: COMPOSITION
We can compose many ways
const getCheeseFromCow = getMilk |> getCheese
const getPizzaFromMilk = getCheese |> getPizza
const makePizza = getMilk |> getCheese |> getPizza
CHAPTER 4: COMPOSITION
Real world example (Normal way)
const sayHello = (name) => ‘Hello ' + name;
const addExcitement = (str) => str + ' !!!!!!!!!!!';
Normal way
const capitalize = (str) => str.toUpperCase();
const name = 'nfq';
const capName = capitalize(name); // 'NFQ'
const withHello = sayHello(capName); // 'Hello NFQ'
const finalString = addExcitement(withHello);
// 'Hello NFQ !!!!!!!!!'
CHAPTER 4: COMPOSITION
Real world example (Functional Javascript way)
const sayHello = (name) => ‘Hello ‘ + name;
const addExcitement = (str) => str + ' !!!!!!!!!!!';
Crazy way
const capitalize = (str) => str.toUpperCase();
const name = 'nfq';
const transform = _.flow([
capitalize, sayHello, addExcitement
]);
transform(name); // 'Hello NFQ !!!!!!!!!'
CHAPTER 4: COMPOSITION
Real world example (Functional Haskell way)
let capitalize name = map toUpper name
let sayHello name = "Hello " ++ name
let addExcitement sentence = sentence ++ " !!!!!”
addExcitement . sayHello . capitalize $ "nfq"
-- "Hello NFQ !!!!!"
CHAPTER 4: COMPOSITION
Benefits of composition
Avoid naming, one of the hardest things in computer science
Encourage us to writer very small functions that do just one thing
Shorter than traditional method
LOOP
CHAPTER 5
CHAPTER 5: LOOP
In functional languages, we don’t use For loop
In functional languages, everything map and reduce (sometimes recursion)
The first step to learn a functional language is trying not to use loop
WHY?
CHAPTER 5: LOOP
1. For loop is usually longer and duplicated (example 1)
var input = [1, 2, 3, 4];
var output = [];
for (var n of input) {
output.push(n + 1);
}
console.log(output); // [2, 3, 4, 5]
var input = [1, 2, 3, 4];
var output = input.map(n => n + 1);
console.log(output); // [2, 3, 4, 5]
CHAPTER 5: LOOP
1. For loop is usually longer and duplicated (example 2)
var input = [1, 2, 3, 4];
var output = [];
for (var n of input) {
if (n % 2 === 0) {
output.push(n);
}
}
console.log(output); // [2, 4]
var input = [1, 2, 3, 4];
var output = input.filter(n => n % 2 === 0);
console.log(output); // [2, 4]
CHAPTER 5: LOOP
1. For loop is usually longer and duplicated (example 3)
var input = [1, 2, 3, 4];
var result = null;
for (var n of input) {
if (n === 3) {
result = n;
break;
}
}
console.log(result); // 3
var input = [1, 2, 3, 4];
var result = input.find(n => n === 3);
console.log(result); // 3
CHAPTER 5: LOOP
2. Map/Filter/Reduce can be made to run in parallel
CHAPTER 5: LOOP
2. For loop cannot be run in parallel easily
… because all the threads still refer to the output variable,
and they must run one by one to maintain orders
CHAPTER 5: LOOP
3. For loop modifies the output object
… which violates a very important property of
Functional Programming:
Immutability
IMMUTABILITY
CHAPTER 6
CHAPTER 6: IMMUTABILITY
What is immutability like in OOP languages?
1. Programming without setter methods
2. Everything is initiated once in the constructor
3. Create a new object, always
CHAPTER 6: IMMUTABILITY
Reason 1: You can debug easier
var person = new Person({
firstName: 'John',
lastName: 'Doe'
});
person.getFullName();
// null
There are only two
possible places
where I did wrong
In the constructor
In the getter
CHAPTER 6: IMMUTABILITY
Reason 1: You can debug easier
var person = new Person();
person.setFirstName('John');
person.setLastName('Doe');
person.getFullName();
// null
There are only four
possible places
where I did wrong
In the constructor
In the setter
In the other setter
In the getter
CHAPTER 6: IMMUTABILITY
Reason 2: Temporal Coupling
person.setLastName('Doe');
person.getFullName();
// null
Things get complicated in multi-threaded environment
person.setFirstName('John');
var person = new Person();
THREAD 1 THREAD 2
CHAPTER 6: IMMUTABILITY
Reason 2: Temporal Coupling
happens when the orders of execution are dependent on each other
var person = new Person();
person.setFirstName('John');
person.setLastName('Doe');
person.getFullName(); // null
1. You have to remember to call setters before calling getter.

Even if you don't, program stills run, and you get run-time error
2. Your getter functions will now include a lot of if-else
CHAPTER 6: IMMUTABILITY
Reason 2: Temporal Coupling
Immutability removes Temporal coupling completely
class Person {
constructor({ firstName, lastName }) {
if (!firstname) throw ...;
if (!lastName) throw ...;
}
getFullName() {
return this.firstName + this.lastName;
}
}
THE END
CONCLUSION
▸ Functions in FP languages are first-class: it can be assigned to
variables, can be passed to another functions
▸ Composition helps avoid naming and encourage writing small
functions
▸ We don't use loop, seriously. Map/Reduce can run in parallel
freely and is shorter to write
▸ Immutability is the required in FP language to avoid concurrency
bugs and temporal coupling
▸ Functional programming encourages writing Pure functions

More Related Content

What's hot

Introducing PHP Latest Updates
Introducing PHP Latest UpdatesIntroducing PHP Latest Updates
Introducing PHP Latest Updates
Iftekhar Eather
 
JavaScript - new features in ECMAScript 6
JavaScript - new features in ECMAScript 6JavaScript - new features in ECMAScript 6
JavaScript - new features in ECMAScript 6
Solution4Future
 
Good Evils In Perl (Yapc Asia)
Good Evils In Perl (Yapc Asia)Good Evils In Perl (Yapc Asia)
Good Evils In Perl (Yapc Asia)
Kang-min Liu
 
What's new in PHP 5.5
What's new in PHP 5.5What's new in PHP 5.5
What's new in PHP 5.5
Tom Corrigan
 

What's hot (20)

Python Programming Essentials - M8 - String Methods
Python Programming Essentials - M8 - String MethodsPython Programming Essentials - M8 - String Methods
Python Programming Essentials - M8 - String Methods
 
ES2015 (ES6) Overview
ES2015 (ES6) OverviewES2015 (ES6) Overview
ES2015 (ES6) Overview
 
Code Generation in PHP - PHPConf 2015
Code Generation in PHP - PHPConf 2015Code Generation in PHP - PHPConf 2015
Code Generation in PHP - PHPConf 2015
 
Shell programming 2
Shell programming 2Shell programming 2
Shell programming 2
 
Shell programming 2
Shell programming 2Shell programming 2
Shell programming 2
 
Introducing PHP Latest Updates
Introducing PHP Latest UpdatesIntroducing PHP Latest Updates
Introducing PHP Latest Updates
 
FParsec Hands On - F#unctional Londoners 2014
FParsec Hands On -  F#unctional Londoners 2014FParsec Hands On -  F#unctional Londoners 2014
FParsec Hands On - F#unctional Londoners 2014
 
From object oriented to functional domain modeling
From object oriented to functional domain modelingFrom object oriented to functional domain modeling
From object oriented to functional domain modeling
 
The Sincerest Form of Flattery
The Sincerest Form of FlatteryThe Sincerest Form of Flattery
The Sincerest Form of Flattery
 
Lambdas and Streams Master Class Part 2
Lambdas and Streams Master Class Part 2Lambdas and Streams Master Class Part 2
Lambdas and Streams Master Class Part 2
 
Introduction to Ecmascript - ES6
Introduction to Ecmascript - ES6Introduction to Ecmascript - ES6
Introduction to Ecmascript - ES6
 
A swift introduction to Swift
A swift introduction to SwiftA swift introduction to Swift
A swift introduction to Swift
 
Lambda and Stream Master class - part 1
Lambda and Stream Master class - part 1Lambda and Stream Master class - part 1
Lambda and Stream Master class - part 1
 
JavaScript - new features in ECMAScript 6
JavaScript - new features in ECMAScript 6JavaScript - new features in ECMAScript 6
JavaScript - new features in ECMAScript 6
 
Swift Programming Language
Swift Programming LanguageSwift Programming Language
Swift Programming Language
 
Good Evils In Perl (Yapc Asia)
Good Evils In Perl (Yapc Asia)Good Evils In Perl (Yapc Asia)
Good Evils In Perl (Yapc Asia)
 
ECMAScript 6
ECMAScript 6ECMAScript 6
ECMAScript 6
 
Clean code
Clean codeClean code
Clean code
 
What's new in PHP 5.5
What's new in PHP 5.5What's new in PHP 5.5
What's new in PHP 5.5
 
DRYing to Monad in Java8
DRYing to Monad in Java8DRYing to Monad in Java8
DRYing to Monad in Java8
 

Similar to Introduction to Functional Programming

Orlando BarCamp Why Javascript Doesn't Suck
Orlando BarCamp Why Javascript Doesn't SuckOrlando BarCamp Why Javascript Doesn't Suck
Orlando BarCamp Why Javascript Doesn't Suck
erockendude
 

Similar to Introduction to Functional Programming (20)

Javascript tid-bits
Javascript tid-bitsJavascript tid-bits
Javascript tid-bits
 
Introduction to kotlin and OOP in Kotlin
Introduction to kotlin and OOP in KotlinIntroduction to kotlin and OOP in Kotlin
Introduction to kotlin and OOP in Kotlin
 
JavaFXScript
JavaFXScriptJavaFXScript
JavaFXScript
 
Workshop 10: ECMAScript 6
Workshop 10: ECMAScript 6Workshop 10: ECMAScript 6
Workshop 10: ECMAScript 6
 
Introduction to Functional Programming (w/ JS)
Introduction to Functional Programming (w/ JS)Introduction to Functional Programming (w/ JS)
Introduction to Functional Programming (w/ JS)
 
ES6 - Next Generation Javascript
ES6 - Next Generation JavascriptES6 - Next Generation Javascript
ES6 - Next Generation Javascript
 
Design Pattern Observations
Design Pattern ObservationsDesign Pattern Observations
Design Pattern Observations
 
Exploring Ceylon with Gavin King - JUG BB Talk - Belrin 2014
Exploring Ceylon with Gavin King - JUG BB Talk - Belrin 2014Exploring Ceylon with Gavin King - JUG BB Talk - Belrin 2014
Exploring Ceylon with Gavin King - JUG BB Talk - Belrin 2014
 
Beauty and Power of Go
Beauty and Power of GoBeauty and Power of Go
Beauty and Power of Go
 
Impress Your Friends with EcmaScript 2015
Impress Your Friends with EcmaScript 2015Impress Your Friends with EcmaScript 2015
Impress Your Friends with EcmaScript 2015
 
Exploring ES6
Exploring ES6Exploring ES6
Exploring ES6
 
2007 09 10 Fzi Training Groovy Grails V Ws
2007 09 10 Fzi Training Groovy Grails V Ws2007 09 10 Fzi Training Groovy Grails V Ws
2007 09 10 Fzi Training Groovy Grails V Ws
 
Orlando BarCamp Why Javascript Doesn't Suck
Orlando BarCamp Why Javascript Doesn't SuckOrlando BarCamp Why Javascript Doesn't Suck
Orlando BarCamp Why Javascript Doesn't Suck
 
Groovy for Java Developers
Groovy for Java DevelopersGroovy for Java Developers
Groovy for Java Developers
 
Licão 13 functions
Licão 13 functionsLicão 13 functions
Licão 13 functions
 
What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)
 
Explaining ES6: JavaScript History and What is to Come
Explaining ES6: JavaScript History and What is to ComeExplaining ES6: JavaScript History and What is to Come
Explaining ES6: JavaScript History and What is to Come
 
ES6: Features + Rails
ES6: Features + RailsES6: Features + Rails
ES6: Features + Rails
 
Go OO! - Real-life Design Patterns in PHP 5
Go OO! - Real-life Design Patterns in PHP 5Go OO! - Real-life Design Patterns in PHP 5
Go OO! - Real-life Design Patterns in PHP 5
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript Introduction
 

Recently uploaded

%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
masabamasaba
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
masabamasaba
 
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
masabamasaba
 
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Medical / Health Care (+971588192166) Mifepristone and Misoprostol tablets 200mg
 

Recently uploaded (20)

WSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open Source
WSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open SourceWSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open Source
WSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open Source
 
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
 
What Goes Wrong with Language Definitions and How to Improve the Situation
What Goes Wrong with Language Definitions and How to Improve the SituationWhat Goes Wrong with Language Definitions and How to Improve the Situation
What Goes Wrong with Language Definitions and How to Improve the Situation
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
 
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
 
WSO2Con204 - Hard Rock Presentation - Keynote
WSO2Con204 - Hard Rock Presentation - KeynoteWSO2Con204 - Hard Rock Presentation - Keynote
WSO2Con204 - Hard Rock Presentation - Keynote
 
WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...
WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...
WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand
 
Architecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastArchitecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the past
 
WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?
 
%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto
 
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
 
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...
 
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
 
WSO2CON 2024 Slides - Open Source to SaaS
WSO2CON 2024 Slides - Open Source to SaaSWSO2CON 2024 Slides - Open Source to SaaS
WSO2CON 2024 Slides - Open Source to SaaS
 
Announcing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareAnnouncing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK Software
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
 

Introduction to Functional Programming

  • 4. CHAPTER 1: INTRODUCTION USAGE IN INDUSTRY Haskell is the most famous functional language. It is being many big companies like Facebook, Microsoft, AT&T as internal tools Erlang / Elixir is the first-class choice for concurrency because of its Actor Model. It’s most used in telecom industry and chat services (Facebook, Whatsapp, Discord, Heroku, RabbitMQ, …) Clojure belongs to LISP family and runs on JVM. It’s being used by CircleCI, SoundCloud, Groupon, Weebly, , Netflix. Clojure is good for concurrency with concepts like Persistent Data Structure and Software Transational Memory Scala is the solid choice for those who seek comfort in both Functional and Object Oriented. It’s in use by big companies like: Twitter, Foursquare, Soundcloud, 9GAG, Tumblr,…
  • 6. CHAPTER 2: PURITY Functional Languages favors “pure function” A pure function is a function that: - Output only depends on Input - Has no side effects
  • 7. CHAPTER 2: PURITY examples of pure functions: function sayHello(name) { return "Hello " + name; } var name = "Lam"; function sayHello() { return "Hello " + name; } function sayHello() { return "Hello " + this.name; } examples of impure functions:
  • 8. CHAPTER 2: PURITY why pure functions matter Pure function is deterministic, it always returns the same output for the same input It’s easy to understand and easy to test Pure functions can be cached, impure functions cannot
  • 10. CHAPTER 3: FIRST-CLASS FUNCTIONS In Functional Languages, we don't strictly follow S-V-O OOP Subject.Verb (Object) alice.SaysHelloTo("Bob") Functional Verb (Subject, Object) SaysHelloTo(alice, ”Bob”)
  • 11. CHAPTER 3: FIRST-CLASS FUNCTIONS In Functional Languages, functions are first-class - It can be assigned to a variable - It can be passed into other function - We can return a function from another function First-class means that, functions plays an equal role as objects:
  • 12. CHAPTER 3: FIRST-CLASS FUNCTIONS Functions as objects <?php $foo = function() { return "Hello World"; }; $foo(); // 'Hello world’ call_user_func($foo); // 'Hello world’ const hello = () => 'Hello World'; const foo = hello; const bar = foo; bar(); // 'Hello world’ bar.call(); // 'Hello world’ bar.length; // 1 Available in most programming languages
  • 13. CHAPTER 3: FIRST-CLASS FUNCTIONS Returning a function from a function function add(number1) { return function(number2) { return number1 + number2; } } add(3)(5) // 8 // instead of add(3, 5) This is called Curry-ing, which is named after Haskell Curry It helps you to build up function and gives name to those functions var increment = add(1); // . . . // meanwhile, in another code increment(2) // 3
  • 14. CHAPTER 3: FIRST-CLASS FUNCTIONS Passing function to another function const whatToDoToday = (what) => { return 'I am ' + what() // ‘I am doing TedTalk' }; const action = random() > 0.5 ? () => 'doing TedTalk' : () => 'doing Nothing'; whatToDoToday(action); In Javascript, function can be passed into other functions.
  • 15. CHAPTER 3: FIRST-CLASS FUNCTIONS First-Class Function is so powerful that in most Functional Languages, GoF Design Patterns do not exist
  • 17. CHAPTER 4: COMPOSITION Function Composition (Cow) =>getMilk = Milk (Milk) =>getCheese = Cheese (Cheese) =>getPizza = Pizza const getCheeseFromCow = getMilk |> getCheese
  • 18. CHAPTER 4: COMPOSITION We can compose many ways const getCheeseFromCow = getMilk |> getCheese const getPizzaFromMilk = getCheese |> getPizza const makePizza = getMilk |> getCheese |> getPizza
  • 19. CHAPTER 4: COMPOSITION Real world example (Normal way) const sayHello = (name) => ‘Hello ' + name; const addExcitement = (str) => str + ' !!!!!!!!!!!'; Normal way const capitalize = (str) => str.toUpperCase(); const name = 'nfq'; const capName = capitalize(name); // 'NFQ' const withHello = sayHello(capName); // 'Hello NFQ' const finalString = addExcitement(withHello); // 'Hello NFQ !!!!!!!!!'
  • 20. CHAPTER 4: COMPOSITION Real world example (Functional Javascript way) const sayHello = (name) => ‘Hello ‘ + name; const addExcitement = (str) => str + ' !!!!!!!!!!!'; Crazy way const capitalize = (str) => str.toUpperCase(); const name = 'nfq'; const transform = _.flow([ capitalize, sayHello, addExcitement ]); transform(name); // 'Hello NFQ !!!!!!!!!'
  • 21. CHAPTER 4: COMPOSITION Real world example (Functional Haskell way) let capitalize name = map toUpper name let sayHello name = "Hello " ++ name let addExcitement sentence = sentence ++ " !!!!!” addExcitement . sayHello . capitalize $ "nfq" -- "Hello NFQ !!!!!"
  • 22. CHAPTER 4: COMPOSITION Benefits of composition Avoid naming, one of the hardest things in computer science Encourage us to writer very small functions that do just one thing Shorter than traditional method
  • 24. CHAPTER 5: LOOP In functional languages, we don’t use For loop In functional languages, everything map and reduce (sometimes recursion) The first step to learn a functional language is trying not to use loop WHY?
  • 25. CHAPTER 5: LOOP 1. For loop is usually longer and duplicated (example 1) var input = [1, 2, 3, 4]; var output = []; for (var n of input) { output.push(n + 1); } console.log(output); // [2, 3, 4, 5] var input = [1, 2, 3, 4]; var output = input.map(n => n + 1); console.log(output); // [2, 3, 4, 5]
  • 26. CHAPTER 5: LOOP 1. For loop is usually longer and duplicated (example 2) var input = [1, 2, 3, 4]; var output = []; for (var n of input) { if (n % 2 === 0) { output.push(n); } } console.log(output); // [2, 4] var input = [1, 2, 3, 4]; var output = input.filter(n => n % 2 === 0); console.log(output); // [2, 4]
  • 27. CHAPTER 5: LOOP 1. For loop is usually longer and duplicated (example 3) var input = [1, 2, 3, 4]; var result = null; for (var n of input) { if (n === 3) { result = n; break; } } console.log(result); // 3 var input = [1, 2, 3, 4]; var result = input.find(n => n === 3); console.log(result); // 3
  • 28. CHAPTER 5: LOOP 2. Map/Filter/Reduce can be made to run in parallel
  • 29. CHAPTER 5: LOOP 2. For loop cannot be run in parallel easily … because all the threads still refer to the output variable, and they must run one by one to maintain orders
  • 30. CHAPTER 5: LOOP 3. For loop modifies the output object … which violates a very important property of Functional Programming: Immutability
  • 32. CHAPTER 6: IMMUTABILITY What is immutability like in OOP languages? 1. Programming without setter methods 2. Everything is initiated once in the constructor 3. Create a new object, always
  • 33. CHAPTER 6: IMMUTABILITY Reason 1: You can debug easier var person = new Person({ firstName: 'John', lastName: 'Doe' }); person.getFullName(); // null There are only two possible places where I did wrong In the constructor In the getter
  • 34. CHAPTER 6: IMMUTABILITY Reason 1: You can debug easier var person = new Person(); person.setFirstName('John'); person.setLastName('Doe'); person.getFullName(); // null There are only four possible places where I did wrong In the constructor In the setter In the other setter In the getter
  • 35. CHAPTER 6: IMMUTABILITY Reason 2: Temporal Coupling person.setLastName('Doe'); person.getFullName(); // null Things get complicated in multi-threaded environment person.setFirstName('John'); var person = new Person(); THREAD 1 THREAD 2
  • 36. CHAPTER 6: IMMUTABILITY Reason 2: Temporal Coupling happens when the orders of execution are dependent on each other var person = new Person(); person.setFirstName('John'); person.setLastName('Doe'); person.getFullName(); // null 1. You have to remember to call setters before calling getter.
 Even if you don't, program stills run, and you get run-time error 2. Your getter functions will now include a lot of if-else
  • 37. CHAPTER 6: IMMUTABILITY Reason 2: Temporal Coupling Immutability removes Temporal coupling completely class Person { constructor({ firstName, lastName }) { if (!firstname) throw ...; if (!lastName) throw ...; } getFullName() { return this.firstName + this.lastName; } }
  • 38. THE END CONCLUSION ▸ Functions in FP languages are first-class: it can be assigned to variables, can be passed to another functions ▸ Composition helps avoid naming and encourage writing small functions ▸ We don't use loop, seriously. Map/Reduce can run in parallel freely and is shorter to write ▸ Immutability is the required in FP language to avoid concurrency bugs and temporal coupling ▸ Functional programming encourages writing Pure functions