SlideShare a Scribd company logo
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
Ad

Recommended

Expression trees in c#
Expression trees in c#
Oleksii Holub
 
Javascript development done right
Javascript development done right
Pawel Szulc
 
Expression trees in c#, Алексей Голубь (Svitla Systems)
Expression trees in c#, Алексей Голубь (Svitla Systems)
Alina Vilk
 
What's New in PHP 5.5
What's New in PHP 5.5
Corey Ballou
 
Java Full Throttle
Java Full Throttle
José Paumard
 
Currying and Partial Function Application (PFA)
Currying and Partial Function Application (PFA)
Dhaval Dalal
 
OSDC.TW - Gutscript for PHP haters
OSDC.TW - Gutscript for PHP haters
Lin Yo-An
 
Creating Lazy stream in CSharp
Creating Lazy stream in CSharp
Dhaval Dalal
 
Python Programming Essentials - M8 - String Methods
Python Programming Essentials - M8 - String Methods
P3 InfoTech Solutions Pvt. Ltd.
 
ES2015 (ES6) Overview
ES2015 (ES6) Overview
hesher
 
Code Generation in PHP - PHPConf 2015
Code Generation in PHP - PHPConf 2015
Lin Yo-An
 
Shell programming 2
Shell programming 2
Kalkey
 
Shell programming 2
Shell programming 2
Gourav Varma
 
Introducing PHP Latest Updates
Introducing PHP Latest Updates
Iftekhar Eather
 
FParsec Hands On - F#unctional Londoners 2014
FParsec Hands On - F#unctional Londoners 2014
Phillip Trelford
 
From object oriented to functional domain modeling
From object oriented to functional domain modeling
Mario Fusco
 
The Sincerest Form of Flattery
The Sincerest Form of Flattery
José Paumard
 
Lambdas and Streams Master Class Part 2
Lambdas and Streams Master Class Part 2
José Paumard
 
Introduction to Ecmascript - ES6
Introduction to Ecmascript - ES6
Nilesh Jayanandana
 
A swift introduction to Swift
A swift introduction to Swift
Giordano Scalzo
 
Lambda and Stream Master class - part 1
Lambda and Stream Master class - part 1
José Paumard
 
JavaScript - new features in ECMAScript 6
JavaScript - new features in ECMAScript 6
Solution4Future
 
Swift Programming Language
Swift Programming Language
Giuseppe Arici
 
Good Evils In Perl (Yapc Asia)
Good Evils In Perl (Yapc Asia)
Kang-min Liu
 
ECMAScript 6
ECMAScript 6
Piotr Lewandowski
 
Clean code
Clean code
ifnu bima
 
What's new in PHP 5.5
What's new in PHP 5.5
Tom Corrigan
 
DRYing to Monad in Java8
DRYing to Monad in Java8
Dhaval Dalal
 
Javascript tid-bits
Javascript tid-bits
David Atchley
 
Introduction to kotlin and OOP in Kotlin
Introduction to kotlin and OOP in Kotlin
vriddhigupta
 

More Related Content

What's hot (20)

Python Programming Essentials - M8 - String Methods
Python Programming Essentials - M8 - String Methods
P3 InfoTech Solutions Pvt. Ltd.
 
ES2015 (ES6) Overview
ES2015 (ES6) Overview
hesher
 
Code Generation in PHP - PHPConf 2015
Code Generation in PHP - PHPConf 2015
Lin Yo-An
 
Shell programming 2
Shell programming 2
Kalkey
 
Shell programming 2
Shell programming 2
Gourav Varma
 
Introducing PHP Latest Updates
Introducing PHP Latest Updates
Iftekhar Eather
 
FParsec Hands On - F#unctional Londoners 2014
FParsec Hands On - F#unctional Londoners 2014
Phillip Trelford
 
From object oriented to functional domain modeling
From object oriented to functional domain modeling
Mario Fusco
 
The Sincerest Form of Flattery
The Sincerest Form of Flattery
José Paumard
 
Lambdas and Streams Master Class Part 2
Lambdas and Streams Master Class Part 2
José Paumard
 
Introduction to Ecmascript - ES6
Introduction to Ecmascript - ES6
Nilesh Jayanandana
 
A swift introduction to Swift
A swift introduction to Swift
Giordano Scalzo
 
Lambda and Stream Master class - part 1
Lambda and Stream Master class - part 1
José Paumard
 
JavaScript - new features in ECMAScript 6
JavaScript - new features in ECMAScript 6
Solution4Future
 
Swift Programming Language
Swift Programming Language
Giuseppe Arici
 
Good Evils In Perl (Yapc Asia)
Good Evils In Perl (Yapc Asia)
Kang-min Liu
 
ECMAScript 6
ECMAScript 6
Piotr Lewandowski
 
Clean code
Clean code
ifnu bima
 
What's new in PHP 5.5
What's new in PHP 5.5
Tom Corrigan
 
DRYing to Monad in Java8
DRYing to Monad in Java8
Dhaval Dalal
 
ES2015 (ES6) Overview
ES2015 (ES6) Overview
hesher
 
Code Generation in PHP - PHPConf 2015
Code Generation in PHP - PHPConf 2015
Lin Yo-An
 
Shell programming 2
Shell programming 2
Kalkey
 
Shell programming 2
Shell programming 2
Gourav Varma
 
Introducing PHP Latest Updates
Introducing PHP Latest Updates
Iftekhar Eather
 
FParsec Hands On - F#unctional Londoners 2014
FParsec Hands On - F#unctional Londoners 2014
Phillip Trelford
 
From object oriented to functional domain modeling
From object oriented to functional domain modeling
Mario Fusco
 
The Sincerest Form of Flattery
The Sincerest Form of Flattery
José Paumard
 
Lambdas and Streams Master Class Part 2
Lambdas and Streams Master Class Part 2
José Paumard
 
Introduction to Ecmascript - ES6
Introduction to Ecmascript - ES6
Nilesh Jayanandana
 
A swift introduction to Swift
A swift introduction to Swift
Giordano Scalzo
 
Lambda and Stream Master class - part 1
Lambda and Stream Master class - part 1
José Paumard
 
JavaScript - new features in ECMAScript 6
JavaScript - new features in ECMAScript 6
Solution4Future
 
Swift Programming Language
Swift Programming Language
Giuseppe Arici
 
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.5
Tom Corrigan
 
DRYing to Monad in Java8
DRYing to Monad in Java8
Dhaval Dalal
 

Similar to Introduction to Functional Programming (20)

Javascript tid-bits
Javascript tid-bits
David Atchley
 
Introduction to kotlin and OOP in Kotlin
Introduction to kotlin and OOP in Kotlin
vriddhigupta
 
JavaFXScript
JavaFXScript
webuploader
 
Workshop 10: ECMAScript 6
Workshop 10: ECMAScript 6
Visual Engineering
 
Introduction to Functional Programming (w/ JS)
Introduction to Functional Programming (w/ JS)
Allan Marques Baptista
 
ES6 - Next Generation Javascript
ES6 - Next Generation Javascript
RameshNair6
 
Design Pattern Observations
Design Pattern Observations
Dmitri Nesteruk
 
Exploring Ceylon with Gavin King - JUG BB Talk - Belrin 2014
Exploring Ceylon with Gavin King - JUG BB Talk - Belrin 2014
hwilming
 
Beauty and Power of Go
Beauty and Power of Go
Frank Müller
 
polymorphism for b.tech iii year students
polymorphism for b.tech iii year students
Somesh Kumar
 
Impress Your Friends with EcmaScript 2015
Impress Your Friends with EcmaScript 2015
Lukas Ruebbelke
 
Exploring ES6
Exploring ES6
Ximing Dai
 
2007 09 10 Fzi Training Groovy Grails V Ws
2007 09 10 Fzi Training Groovy Grails V Ws
loffenauer
 
Orlando BarCamp Why Javascript Doesn't Suck
Orlando BarCamp Why Javascript Doesn't Suck
erockendude
 
Groovy for Java Developers
Groovy for Java Developers
Andres Almiray
 
Licão 13 functions
Licão 13 functions
Acácio Oliveira
 
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)
Pavlo Baron
 
Explaining ES6: JavaScript History and What is to Come
Explaining ES6: JavaScript History and What is to Come
Cory Forsyth
 
ES6: Features + Rails
ES6: Features + Rails
Santosh Wadghule
 
Go OO! - Real-life Design Patterns in PHP 5
Go OO! - Real-life Design Patterns in PHP 5
Stephan Schmidt
 
Introduction to kotlin and OOP in Kotlin
Introduction to kotlin and OOP in Kotlin
vriddhigupta
 
Introduction to Functional Programming (w/ JS)
Introduction to Functional Programming (w/ JS)
Allan Marques Baptista
 
ES6 - Next Generation Javascript
ES6 - Next Generation Javascript
RameshNair6
 
Design Pattern Observations
Design Pattern Observations
Dmitri Nesteruk
 
Exploring Ceylon with Gavin King - JUG BB Talk - Belrin 2014
Exploring Ceylon with Gavin King - JUG BB Talk - Belrin 2014
hwilming
 
Beauty and Power of Go
Beauty and Power of Go
Frank Müller
 
polymorphism for b.tech iii year students
polymorphism for b.tech iii year students
Somesh Kumar
 
Impress Your Friends with EcmaScript 2015
Impress Your Friends with EcmaScript 2015
Lukas Ruebbelke
 
2007 09 10 Fzi Training Groovy Grails V Ws
2007 09 10 Fzi Training Groovy Grails V Ws
loffenauer
 
Orlando BarCamp Why Javascript Doesn't Suck
Orlando BarCamp Why Javascript Doesn't Suck
erockendude
 
Groovy for Java Developers
Groovy for Java Developers
Andres Almiray
 
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)
Pavlo Baron
 
Explaining ES6: JavaScript History and What is to Come
Explaining ES6: JavaScript History and What is to Come
Cory Forsyth
 
Go OO! - Real-life Design Patterns in PHP 5
Go OO! - Real-life Design Patterns in PHP 5
Stephan Schmidt
 
Ad

Recently uploaded (20)

Zoneranker’s Digital marketing solutions
Zoneranker’s Digital marketing solutions
reenashriee
 
Building Geospatial Data Warehouse for GIS by GIS with FME
Building Geospatial Data Warehouse for GIS by GIS with FME
Safe Software
 
Azure AI Foundry: The AI app and agent factory
Azure AI Foundry: The AI app and agent factory
Maxim Salnikov
 
Introduction to Agile Frameworks for Product Managers.pdf
Introduction to Agile Frameworks for Product Managers.pdf
Ali Vahed
 
Modern Platform Engineering with Choreo - The AI-Native Internal Developer Pl...
Modern Platform Engineering with Choreo - The AI-Native Internal Developer Pl...
WSO2
 
Why Every Growing Business Needs a Staff Augmentation Company IN USA.pdf
Why Every Growing Business Needs a Staff Augmentation Company IN USA.pdf
mary rojas
 
ERP Systems in the UAE: Driving Business Transformation with Smart Solutions
ERP Systems in the UAE: Driving Business Transformation with Smart Solutions
dheeodoo
 
Simplify Task, Team, and Project Management with Orangescrum Work
Simplify Task, Team, and Project Management with Orangescrum Work
Orangescrum
 
Reimagining Software Development and DevOps with Agentic AI
Reimagining Software Development and DevOps with Agentic AI
Maxim Salnikov
 
SAP PM Module Level-IV Training Complete.ppt
SAP PM Module Level-IV Training Complete.ppt
MuhammadShaheryar36
 
ElectraSuite_Prsentation(online voting system).pptx
ElectraSuite_Prsentation(online voting system).pptx
mrsinankhan01
 
Best Practice for LLM Serving in the Cloud
Best Practice for LLM Serving in the Cloud
Alluxio, Inc.
 
Application Modernization with Choreo - The AI-Native Internal Developer Plat...
Application Modernization with Choreo - The AI-Native Internal Developer Plat...
WSO2
 
arctitecture application system design os dsa
arctitecture application system design os dsa
za241967
 
OpenChain Webinar - AboutCode - Practical Compliance in One Stack – Licensing...
OpenChain Webinar - AboutCode - Practical Compliance in One Stack – Licensing...
Shane Coughlan
 
From Data Preparation to Inference: How Alluxio Speeds Up AI
From Data Preparation to Inference: How Alluxio Speeds Up AI
Alluxio, Inc.
 
Download Adobe Illustrator Crack free for Windows 2025?
Download Adobe Illustrator Crack free for Windows 2025?
grete1122g
 
CodeCleaner: Mitigating Data Contamination for LLM Benchmarking
CodeCleaner: Mitigating Data Contamination for LLM Benchmarking
arabelatso
 
Decipher SEO Solutions for your startup needs.
Decipher SEO Solutions for your startup needs.
mathai2
 
The Anti-Masterclass Live - Peak of Data & AI 2025
The Anti-Masterclass Live - Peak of Data & AI 2025
Safe Software
 
Zoneranker’s Digital marketing solutions
Zoneranker’s Digital marketing solutions
reenashriee
 
Building Geospatial Data Warehouse for GIS by GIS with FME
Building Geospatial Data Warehouse for GIS by GIS with FME
Safe Software
 
Azure AI Foundry: The AI app and agent factory
Azure AI Foundry: The AI app and agent factory
Maxim Salnikov
 
Introduction to Agile Frameworks for Product Managers.pdf
Introduction to Agile Frameworks for Product Managers.pdf
Ali Vahed
 
Modern Platform Engineering with Choreo - The AI-Native Internal Developer Pl...
Modern Platform Engineering with Choreo - The AI-Native Internal Developer Pl...
WSO2
 
Why Every Growing Business Needs a Staff Augmentation Company IN USA.pdf
Why Every Growing Business Needs a Staff Augmentation Company IN USA.pdf
mary rojas
 
ERP Systems in the UAE: Driving Business Transformation with Smart Solutions
ERP Systems in the UAE: Driving Business Transformation with Smart Solutions
dheeodoo
 
Simplify Task, Team, and Project Management with Orangescrum Work
Simplify Task, Team, and Project Management with Orangescrum Work
Orangescrum
 
Reimagining Software Development and DevOps with Agentic AI
Reimagining Software Development and DevOps with Agentic AI
Maxim Salnikov
 
SAP PM Module Level-IV Training Complete.ppt
SAP PM Module Level-IV Training Complete.ppt
MuhammadShaheryar36
 
ElectraSuite_Prsentation(online voting system).pptx
ElectraSuite_Prsentation(online voting system).pptx
mrsinankhan01
 
Best Practice for LLM Serving in the Cloud
Best Practice for LLM Serving in the Cloud
Alluxio, Inc.
 
Application Modernization with Choreo - The AI-Native Internal Developer Plat...
Application Modernization with Choreo - The AI-Native Internal Developer Plat...
WSO2
 
arctitecture application system design os dsa
arctitecture application system design os dsa
za241967
 
OpenChain Webinar - AboutCode - Practical Compliance in One Stack – Licensing...
OpenChain Webinar - AboutCode - Practical Compliance in One Stack – Licensing...
Shane Coughlan
 
From Data Preparation to Inference: How Alluxio Speeds Up AI
From Data Preparation to Inference: How Alluxio Speeds Up AI
Alluxio, Inc.
 
Download Adobe Illustrator Crack free for Windows 2025?
Download Adobe Illustrator Crack free for Windows 2025?
grete1122g
 
CodeCleaner: Mitigating Data Contamination for LLM Benchmarking
CodeCleaner: Mitigating Data Contamination for LLM Benchmarking
arabelatso
 
Decipher SEO Solutions for your startup needs.
Decipher SEO Solutions for your startup needs.
mathai2
 
The Anti-Masterclass Live - Peak of Data & AI 2025
The Anti-Masterclass Live - Peak of Data & AI 2025
Safe Software
 
Ad

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