SlideShare ist ein Scribd-Unternehmen logo
1 von 13
Functional Programming
A brief, yet practical introduction
What is functional programming?
● Immutable data, first class functions, currying, mapping, reducing,
pipelining, recursing…
Software composed of pure functions
“
”
Pure Functions
★ A pure function is a function that has no side effects
The function doesn’t rely on data outside the current function, and it
doesn’t change data that exists outside of the current function
★ Given the same inputs, it will always return the same output
“
”
DO everything with functions
Avoid side effects
var potato = 0;
function increment() {
return potato += 1;
}
increment(potato) {
return potato + 1;
}
non-functional
functional
Declarative not imperative
function sumOfSquares(nums) {
var i, sum = 0, squares = [];
for (i = 0; i < nums.length; i++) {
squares.push(nums[i]*nums[i]);
}
for (i = 0; i < squares.length; i++) {
sum += squares[i];
}
return sum;
}
console.log(sumOfSquares([1, 2, 3, 4, 5]));
Imperative
★ Not how, but what to do
Declarative not imperative
function sumOfSquares2(nums) {
return nums
.map(function(num) { return num * num; })
.reduce(function(start, num) { return start + num; }, 0)
;
}
console.log(sumOfSquares([1, 2, 3, 4, 5]));
Declarative
Higher Order functions
★ A function that takes a function as an input or returns a function as output,
or both
function speakTruth(name) {
return function (string) {
return name + “ ” + string;
};
}
var truthifier = speakTruth(“Ed”);
truthifier(“is bad at foos”);
=> “Ed is bad at foos”
Don’t iterate
★ Use map and reduce
A Map takes a function and a collection of items. It
makes a new, empty collection, runs the function on each
item in the original collection, and inserts each return
value into the new collection. It then returns the new
collection.
Map
Reduce takes a function and a collection of
items. It returns a value that is created by
combining the items.
Reduce
Map, an eggjampool
var names = [“Mary”, “Isla”, “Sam”];
var code_names = [“Mr. Pink”, “Mr. Orange”, “Mr. Blonde”];
for(var i in code_names) {
var randomIndex = Math.floor(Math.random() * code_names.length);
var randomValue = code_names[randomIndex];
names[i] = randomValue;
}
console.log(names);
=> ["Mr. Blonde", "Mr. Pink", "Mr. Pink"]
Iterative Approach
Map, an eggjampool cont.
var names = [“Mary”, “Isla”, “Sam”];
var code_names = [“Mr. Pink”, “Mr. Orange”, “Mr. Blonde”];
names = names.map(function(item) {
var randomIndex = Math.floor(Math.random() * code_names.length);
var randomValue = code_names[randomIndex];
return randomValue;
});
console.log(names);
=> ["Mr. Orange", "Mr. Orange", "Mr. Blonde"]
Using Map
Pure Functions, an example
★ A pure function is a function that has no side effects
var a = 0;
function increment() {
return a += 1;
}
increment(a) {
return a + 1;
}
non-functional
functional
The end

Weitere ähnliche Inhalte

Was ist angesagt?

Altitude San Francisco 2018: WebAssembly Tools & Applications
Altitude San Francisco 2018: WebAssembly Tools & ApplicationsAltitude San Francisco 2018: WebAssembly Tools & Applications
Altitude San Francisco 2018: WebAssembly Tools & ApplicationsFastly
 
MS Sql Server: Doing Calculations With Functions
MS Sql Server: Doing Calculations With FunctionsMS Sql Server: Doing Calculations With Functions
MS Sql Server: Doing Calculations With FunctionsDataminingTools Inc
 
16858 memory management2
16858 memory management216858 memory management2
16858 memory management2Aanand Singh
 
Curry functions in Javascript
Curry functions in JavascriptCurry functions in Javascript
Curry functions in JavascriptAnand Kumar
 
random forest regression
random forest regressionrandom forest regression
random forest regressionAkhilesh Joshi
 
Why Haskell Matters
Why Haskell MattersWhy Haskell Matters
Why Haskell Mattersromanandreg
 
Statistics - ArgMax Equation
Statistics - ArgMax EquationStatistics - ArgMax Equation
Statistics - ArgMax EquationAndrew Ferlitsch
 
Programming the cloud with Skywriting
Programming the cloud with SkywritingProgramming the cloud with Skywriting
Programming the cloud with SkywritingDerek Murray
 
Lessons learned from functional programming
Lessons learned from functional programmingLessons learned from functional programming
Lessons learned from functional programmingBryceLohr
 
Add Some Fun to Your Functional Programming With RXJS
Add Some Fun to Your Functional Programming With RXJSAdd Some Fun to Your Functional Programming With RXJS
Add Some Fun to Your Functional Programming With RXJSRyan Anklam
 
(Almost) Serverless Analytics System with BigQuery & AppEngine
(Almost) Serverless Analytics System with BigQuery & AppEngine(Almost) Serverless Analytics System with BigQuery & AppEngine
(Almost) Serverless Analytics System with BigQuery & AppEngineGabriel PREDA
 
2 18-2018-all teams total runs
2 18-2018-all teams total runs2 18-2018-all teams total runs
2 18-2018-all teams total runsAlexander Bitar
 
Use of django at jolt online v3
Use of django at jolt online v3Use of django at jolt online v3
Use of django at jolt online v3Jaime Buelta
 
20160616技術會議
20160616技術會議20160616技術會議
20160616技術會議Jason Kuan
 
Queue Implementation Using Array & Linked List
Queue Implementation Using Array & Linked ListQueue Implementation Using Array & Linked List
Queue Implementation Using Array & Linked ListPTCL
 
Mi primer map reduce
Mi primer map reduceMi primer map reduce
Mi primer map reduceRuben Orta
 

Was ist angesagt? (19)

Python Set.pptx
Python Set.pptxPython Set.pptx
Python Set.pptx
 
Altitude San Francisco 2018: WebAssembly Tools & Applications
Altitude San Francisco 2018: WebAssembly Tools & ApplicationsAltitude San Francisco 2018: WebAssembly Tools & Applications
Altitude San Francisco 2018: WebAssembly Tools & Applications
 
MS Sql Server: Doing Calculations With Functions
MS Sql Server: Doing Calculations With FunctionsMS Sql Server: Doing Calculations With Functions
MS Sql Server: Doing Calculations With Functions
 
16858 memory management2
16858 memory management216858 memory management2
16858 memory management2
 
Uts
UtsUts
Uts
 
Curry functions in Javascript
Curry functions in JavascriptCurry functions in Javascript
Curry functions in Javascript
 
random forest regression
random forest regressionrandom forest regression
random forest regression
 
Why Haskell Matters
Why Haskell MattersWhy Haskell Matters
Why Haskell Matters
 
Statistics - ArgMax Equation
Statistics - ArgMax EquationStatistics - ArgMax Equation
Statistics - ArgMax Equation
 
Programming the cloud with Skywriting
Programming the cloud with SkywritingProgramming the cloud with Skywriting
Programming the cloud with Skywriting
 
Lessons learned from functional programming
Lessons learned from functional programmingLessons learned from functional programming
Lessons learned from functional programming
 
Add Some Fun to Your Functional Programming With RXJS
Add Some Fun to Your Functional Programming With RXJSAdd Some Fun to Your Functional Programming With RXJS
Add Some Fun to Your Functional Programming With RXJS
 
(Almost) Serverless Analytics System with BigQuery & AppEngine
(Almost) Serverless Analytics System with BigQuery & AppEngine(Almost) Serverless Analytics System with BigQuery & AppEngine
(Almost) Serverless Analytics System with BigQuery & AppEngine
 
Queue oop
Queue   oopQueue   oop
Queue oop
 
2 18-2018-all teams total runs
2 18-2018-all teams total runs2 18-2018-all teams total runs
2 18-2018-all teams total runs
 
Use of django at jolt online v3
Use of django at jolt online v3Use of django at jolt online v3
Use of django at jolt online v3
 
20160616技術會議
20160616技術會議20160616技術會議
20160616技術會議
 
Queue Implementation Using Array & Linked List
Queue Implementation Using Array & Linked ListQueue Implementation Using Array & Linked List
Queue Implementation Using Array & Linked List
 
Mi primer map reduce
Mi primer map reduceMi primer map reduce
Mi primer map reduce
 

Ähnlich wie Practical Intro to Functional Programming

Thinking in Functions: Functional Programming in Python
Thinking in Functions: Functional Programming in PythonThinking in Functions: Functional Programming in Python
Thinking in Functions: Functional Programming in PythonAnoop Thomas Mathew
 
Functional Programming with Groovy
Functional Programming with GroovyFunctional Programming with Groovy
Functional Programming with GroovyArturo Herrero
 
Composition in JavaScript
Composition in JavaScriptComposition in JavaScript
Composition in JavaScriptJosh Mock
 
Functional programming basics
Functional programming basicsFunctional programming basics
Functional programming basicsopenbala
 
Functional Programming for OO Programmers (part 2)
Functional Programming for OO Programmers (part 2)Functional Programming for OO Programmers (part 2)
Functional Programming for OO Programmers (part 2)Calvin Cheng
 
Introduction to Kotlin.pptx
Introduction to Kotlin.pptxIntroduction to Kotlin.pptx
Introduction to Kotlin.pptxAzharFauzan9
 
01 Introduction to Kotlin - Programming in Kotlin.pptx
01 Introduction to Kotlin - Programming in Kotlin.pptx01 Introduction to Kotlin - Programming in Kotlin.pptx
01 Introduction to Kotlin - Programming in Kotlin.pptxIvanZawPhyo
 
Learning Functional Programming Without Growing a Neckbeard
Learning Functional Programming Without Growing a NeckbeardLearning Functional Programming Without Growing a Neckbeard
Learning Functional Programming Without Growing a NeckbeardKelsey Gilmore-Innis
 
Functional Programming Patterns (BuildStuff '14)
Functional Programming Patterns (BuildStuff '14)Functional Programming Patterns (BuildStuff '14)
Functional Programming Patterns (BuildStuff '14)Scott Wlaschin
 
Functional Programming in Swift
Functional Programming in SwiftFunctional Programming in Swift
Functional Programming in SwiftSaugat Gautam
 
Five Languages in a Moment
Five Languages in a MomentFive Languages in a Moment
Five Languages in a MomentSergio Gil
 
EcmaScript unchained
EcmaScript unchainedEcmaScript unchained
EcmaScript unchainedEduard Tomàs
 
Something about Golang
Something about GolangSomething about Golang
Something about GolangAnton Arhipov
 
81818088 isc-class-xii-computer-science-project-java-programs
81818088 isc-class-xii-computer-science-project-java-programs81818088 isc-class-xii-computer-science-project-java-programs
81818088 isc-class-xii-computer-science-project-java-programsAbhishek Jena
 
Damn Fine CoffeeScript
Damn Fine CoffeeScriptDamn Fine CoffeeScript
Damn Fine CoffeeScriptniklal
 
design and analysis of algorithm Lab files
design and analysis of algorithm Lab filesdesign and analysis of algorithm Lab files
design and analysis of algorithm Lab filesNitesh Dubey
 

Ähnlich wie Practical Intro to Functional Programming (20)

Short intro to ECMAScript
Short intro to ECMAScriptShort intro to ECMAScript
Short intro to ECMAScript
 
Thinking in Functions: Functional Programming in Python
Thinking in Functions: Functional Programming in PythonThinking in Functions: Functional Programming in Python
Thinking in Functions: Functional Programming in Python
 
Functional Programming with Groovy
Functional Programming with GroovyFunctional Programming with Groovy
Functional Programming with Groovy
 
Composition in JavaScript
Composition in JavaScriptComposition in JavaScript
Composition in JavaScript
 
Fp
FpFp
Fp
 
Functional programming basics
Functional programming basicsFunctional programming basics
Functional programming basics
 
Functional Programming for OO Programmers (part 2)
Functional Programming for OO Programmers (part 2)Functional Programming for OO Programmers (part 2)
Functional Programming for OO Programmers (part 2)
 
Introduction to Kotlin.pptx
Introduction to Kotlin.pptxIntroduction to Kotlin.pptx
Introduction to Kotlin.pptx
 
01 Introduction to Kotlin - Programming in Kotlin.pptx
01 Introduction to Kotlin - Programming in Kotlin.pptx01 Introduction to Kotlin - Programming in Kotlin.pptx
01 Introduction to Kotlin - Programming in Kotlin.pptx
 
Learning Functional Programming Without Growing a Neckbeard
Learning Functional Programming Without Growing a NeckbeardLearning Functional Programming Without Growing a Neckbeard
Learning Functional Programming Without Growing a Neckbeard
 
8558537werr.pptx
8558537werr.pptx8558537werr.pptx
8558537werr.pptx
 
25-functions.ppt
25-functions.ppt25-functions.ppt
25-functions.ppt
 
Functional Programming Patterns (BuildStuff '14)
Functional Programming Patterns (BuildStuff '14)Functional Programming Patterns (BuildStuff '14)
Functional Programming Patterns (BuildStuff '14)
 
Functional Programming in Swift
Functional Programming in SwiftFunctional Programming in Swift
Functional Programming in Swift
 
Five Languages in a Moment
Five Languages in a MomentFive Languages in a Moment
Five Languages in a Moment
 
EcmaScript unchained
EcmaScript unchainedEcmaScript unchained
EcmaScript unchained
 
Something about Golang
Something about GolangSomething about Golang
Something about Golang
 
81818088 isc-class-xii-computer-science-project-java-programs
81818088 isc-class-xii-computer-science-project-java-programs81818088 isc-class-xii-computer-science-project-java-programs
81818088 isc-class-xii-computer-science-project-java-programs
 
Damn Fine CoffeeScript
Damn Fine CoffeeScriptDamn Fine CoffeeScript
Damn Fine CoffeeScript
 
design and analysis of algorithm Lab files
design and analysis of algorithm Lab filesdesign and analysis of algorithm Lab files
design and analysis of algorithm Lab files
 

Kürzlich hochgeladen

What are the features of Vehicle Tracking System?
What are the features of Vehicle Tracking System?What are the features of Vehicle Tracking System?
What are the features of Vehicle Tracking System?Watsoo Telematics
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)OPEN KNOWLEDGE GmbH
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataBradBedford3
 
buds n tech IT solutions
buds n  tech IT                solutionsbuds n  tech IT                solutions
buds n tech IT solutionsmonugehlot87
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio, Inc.
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityNeo4j
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...aditisharan08
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEOrtus Solutions, Corp
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackVICTOR MAESTRE RAMIREZ
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideChristina Lin
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationkaushalgiri8080
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfPower Karaoke
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...Christina Lin
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfjoe51371421
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - InfographicHr365.us smith
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 

Kürzlich hochgeladen (20)

Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 
What are the features of Vehicle Tracking System?
What are the features of Vehicle Tracking System?What are the features of Vehicle Tracking System?
What are the features of Vehicle Tracking System?
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
 
buds n tech IT solutions
buds n  tech IT                solutionsbuds n  tech IT                solutions
buds n tech IT solutions
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered Sustainability
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStack
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanation
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdf
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdf
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - Infographic
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 

Practical Intro to Functional Programming

  • 1. Functional Programming A brief, yet practical introduction
  • 2. What is functional programming? ● Immutable data, first class functions, currying, mapping, reducing, pipelining, recursing… Software composed of pure functions “ ”
  • 3. Pure Functions ★ A pure function is a function that has no side effects The function doesn’t rely on data outside the current function, and it doesn’t change data that exists outside of the current function ★ Given the same inputs, it will always return the same output “ ”
  • 4. DO everything with functions
  • 5. Avoid side effects var potato = 0; function increment() { return potato += 1; } increment(potato) { return potato + 1; } non-functional functional
  • 6. Declarative not imperative function sumOfSquares(nums) { var i, sum = 0, squares = []; for (i = 0; i < nums.length; i++) { squares.push(nums[i]*nums[i]); } for (i = 0; i < squares.length; i++) { sum += squares[i]; } return sum; } console.log(sumOfSquares([1, 2, 3, 4, 5])); Imperative ★ Not how, but what to do
  • 7. Declarative not imperative function sumOfSquares2(nums) { return nums .map(function(num) { return num * num; }) .reduce(function(start, num) { return start + num; }, 0) ; } console.log(sumOfSquares([1, 2, 3, 4, 5])); Declarative
  • 8. Higher Order functions ★ A function that takes a function as an input or returns a function as output, or both function speakTruth(name) { return function (string) { return name + “ ” + string; }; } var truthifier = speakTruth(“Ed”); truthifier(“is bad at foos”); => “Ed is bad at foos”
  • 9. Don’t iterate ★ Use map and reduce A Map takes a function and a collection of items. It makes a new, empty collection, runs the function on each item in the original collection, and inserts each return value into the new collection. It then returns the new collection. Map Reduce takes a function and a collection of items. It returns a value that is created by combining the items. Reduce
  • 10. Map, an eggjampool var names = [“Mary”, “Isla”, “Sam”]; var code_names = [“Mr. Pink”, “Mr. Orange”, “Mr. Blonde”]; for(var i in code_names) { var randomIndex = Math.floor(Math.random() * code_names.length); var randomValue = code_names[randomIndex]; names[i] = randomValue; } console.log(names); => ["Mr. Blonde", "Mr. Pink", "Mr. Pink"] Iterative Approach
  • 11. Map, an eggjampool cont. var names = [“Mary”, “Isla”, “Sam”]; var code_names = [“Mr. Pink”, “Mr. Orange”, “Mr. Blonde”]; names = names.map(function(item) { var randomIndex = Math.floor(Math.random() * code_names.length); var randomValue = code_names[randomIndex]; return randomValue; }); console.log(names); => ["Mr. Orange", "Mr. Orange", "Mr. Blonde"] Using Map
  • 12. Pure Functions, an example ★ A pure function is a function that has no side effects var a = 0; function increment() { return a += 1; } increment(a) { return a + 1; } non-functional functional