SlideShare a Scribd company logo
1 of 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
(Ed is still bad at foos)

More Related Content

What's hot

Curry functions in Javascript
Curry functions in JavascriptCurry functions in Javascript
Curry functions in JavascriptAnand Kumar
 
16858 memory management2
16858 memory management216858 memory management2
16858 memory management2Aanand Singh
 
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
 
random forest regression
random forest regressionrandom forest regression
random forest regressionAkhilesh Joshi
 
行列演算とPythonの言語デザイン
行列演算とPythonの言語デザイン行列演算とPythonの言語デザイン
行列演算とPythonの言語デザインAtsuo Ishimoto
 
Functional Programming
Functional ProgrammingFunctional Programming
Functional Programmingchriseidhof
 
NumPyの歴史とPythonの並行処理【PyData.tokyo One-day Conference 2018】
NumPyの歴史とPythonの並行処理【PyData.tokyo One-day Conference 2018】NumPyの歴史とPythonの並行処理【PyData.tokyo One-day Conference 2018】
NumPyの歴史とPythonの並行処理【PyData.tokyo One-day Conference 2018】Atsuo Ishimoto
 
Programming the cloud with Skywriting
Programming the cloud with SkywritingProgramming the cloud with Skywriting
Programming the cloud with SkywritingDerek Murray
 
Tupple ware in scala
Tupple ware in scalaTupple ware in scala
Tupple ware in scalaVulcanMinds
 
multiple linear regression
multiple linear regressionmultiple linear regression
multiple linear regressionAkhilesh Joshi
 
Queue Implementation Using Array & Linked List
Queue Implementation Using Array & Linked ListQueue Implementation Using Array & Linked List
Queue Implementation Using Array & Linked ListPTCL
 
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
 
String predefined functions in C programming
String predefined functions in C  programmingString predefined functions in C  programming
String predefined functions in C programmingProfSonaliGholveDoif
 
Chapter24 operator-overloading
Chapter24 operator-overloadingChapter24 operator-overloading
Chapter24 operator-overloadingDeepak Singh
 

What's hot (18)

Curry functions in Javascript
Curry functions in JavascriptCurry functions in Javascript
Curry functions in Javascript
 
getdata.pdf
getdata.pdfgetdata.pdf
getdata.pdf
 
16858 memory management2
16858 memory management216858 memory management2
16858 memory management2
 
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
 
Python Set.pptx
Python Set.pptxPython Set.pptx
Python Set.pptx
 
random forest regression
random forest regressionrandom forest regression
random forest regression
 
行列演算とPythonの言語デザイン
行列演算とPythonの言語デザイン行列演算とPythonの言語デザイン
行列演算とPythonの言語デザイン
 
Functional Programming
Functional ProgrammingFunctional Programming
Functional Programming
 
NumPyの歴史とPythonの並行処理【PyData.tokyo One-day Conference 2018】
NumPyの歴史とPythonの並行処理【PyData.tokyo One-day Conference 2018】NumPyの歴史とPythonの並行処理【PyData.tokyo One-day Conference 2018】
NumPyの歴史とPythonの並行処理【PyData.tokyo One-day Conference 2018】
 
Programming the cloud with Skywriting
Programming the cloud with SkywritingProgramming the cloud with Skywriting
Programming the cloud with Skywriting
 
Tupple ware in scala
Tupple ware in scalaTupple ware in scala
Tupple ware in scala
 
Queue oop
Queue   oopQueue   oop
Queue oop
 
multiple linear regression
multiple linear regressionmultiple linear regression
multiple linear regression
 
Queue Implementation Using Array & Linked List
Queue Implementation Using Array & Linked ListQueue Implementation Using Array & Linked List
Queue Implementation Using Array & Linked List
 
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
 
String predefined functions in C programming
String predefined functions in C  programmingString predefined functions in C  programming
String predefined functions in C programming
 
Queue
QueueQueue
Queue
 
Chapter24 operator-overloading
Chapter24 operator-overloadingChapter24 operator-overloading
Chapter24 operator-overloading
 

Similar 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
 
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 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
 
Functional Programming in Swift
Functional Programming in SwiftFunctional Programming in Swift
Functional Programming in SwiftSaugat Gautam
 
Functional Programming Patterns (BuildStuff '14)
Functional Programming Patterns (BuildStuff '14)Functional Programming Patterns (BuildStuff '14)
Functional Programming Patterns (BuildStuff '14)Scott Wlaschin
 
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
 
C++ Searching & Sorting5. Sort the following list using the select.pdf
C++ Searching & Sorting5. Sort the following list using the select.pdfC++ Searching & Sorting5. Sort the following list using the select.pdf
C++ Searching & Sorting5. Sort the following list using the select.pdfRahul04August
 
Functional Programming in JavaScript by Luis Atencio
Functional Programming in JavaScript by Luis AtencioFunctional Programming in JavaScript by Luis Atencio
Functional Programming in JavaScript by Luis AtencioLuis Atencio
 
Functional aspects of java 8
Functional aspects of java 8Functional aspects of java 8
Functional aspects of java 8Jobaer Chowdhury
 

Similar 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
 
Functional programming basics
Functional programming basicsFunctional programming basics
Functional programming basics
 
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
 
Fp
FpFp
Fp
 
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
 
25-functions.ppt
25-functions.ppt25-functions.ppt
25-functions.ppt
 
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)
 
8558537werr.pptx
8558537werr.pptx8558537werr.pptx
8558537werr.pptx
 
Functional Programming in Swift
Functional Programming in SwiftFunctional Programming in Swift
Functional Programming in Swift
 
Functional Programming Patterns (BuildStuff '14)
Functional Programming Patterns (BuildStuff '14)Functional Programming Patterns (BuildStuff '14)
Functional Programming Patterns (BuildStuff '14)
 
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
 
C++ Searching & Sorting5. Sort the following list using the select.pdf
C++ Searching & Sorting5. Sort the following list using the select.pdfC++ Searching & Sorting5. Sort the following list using the select.pdf
C++ Searching & Sorting5. Sort the following list using the select.pdf
 
Functional programming 101
Functional programming 101Functional programming 101
Functional programming 101
 
Functional Programming in JavaScript by Luis Atencio
Functional Programming in JavaScript by Luis AtencioFunctional Programming in JavaScript by Luis Atencio
Functional Programming in JavaScript by Luis Atencio
 
Functional aspects of java 8
Functional aspects of java 8Functional aspects of java 8
Functional aspects of java 8
 

Recently uploaded

What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....kzayra69
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEEVICTOR MAESTRE RAMIREZ
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxTier1 app
 
How to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdfHow to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdfLivetecs LLC
 
Buds n Tech IT Solutions: Top-Notch Web Services in Noida
Buds n Tech IT Solutions: Top-Notch Web Services in NoidaBuds n Tech IT Solutions: Top-Notch Web Services in Noida
Buds n Tech IT Solutions: Top-Notch Web Services in Noidabntitsolutionsrishis
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfFerryKemperman
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based projectAnoyGreter
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceBrainSell Technologies
 
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
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsAhmed Mohamed
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaHanief Utama
 
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Matt Ray
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesPhilip Schwarz
 
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.
 
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
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...soniya singh
 
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
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样umasea
 
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
 

Recently uploaded (20)

What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEE
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
 
How to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdfHow to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdf
 
Buds n Tech IT Solutions: Top-Notch Web Services in Noida
Buds n Tech IT Solutions: Top-Notch Web Services in NoidaBuds n Tech IT Solutions: Top-Notch Web Services in Noida
Buds n Tech IT Solutions: Top-Notch Web Services in Noida
 
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort ServiceHot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdf
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based project
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. Salesforce
 
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...
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML Diagrams
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief Utama
 
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a series
 
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
 
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...
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
 
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
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
 
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
 

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
  • 13. The end (Ed is still bad at foos)