SlideShare a Scribd company logo
Functional
Programming
@bruno_lui
Imperative
programming paradigm
is about . . .
modifying mutable variables
using assignments
and control structures such
as if, then, else, lops, break,
continue, return
Functional
programming paradigm
means ...
modifying mutable variables
assignments
programming without
and other imperative
control structures
programming focusing on
the functions
functions ARE values that
can be produced, consumed
and composed
Principles
and
Concepts
Immutable Data
Functional programs should be immutable,
which means you would simply create new
data structures
instead of modifying ones that already exist.
Referential transparency
Functional programs should perform every task
as if for the first time, with no knowledge of what
may or may not have happened earlier in the
program’s execution and without side effects.
Function as first-class citizens
functions can be defined anywhere
they can be passed as parameters to functions and
returned as results
there exists a set of operators to compose functions
• A number can be stored in a variable and so can a function: 

var fortytwo = function() { return 42 };
• A number can be stored in an array slot and so can a function: 

var fortytwos = [42, function() { return 42 }];
• A number can be stored in an object field and so can a function: 

var fortytwos = {number: 42, fun: function() { return 42 }}; 

• A number can be created as needed and so can a function: 

42 + (function() { return 42 })(); //=> 84
• A number can be passed to a function and so can a function: 

function weirdAdd(n, f) { return n + f() } weirdAdd(42, function() { return 42 }); 

//=> 84 

• A number can be returned from a function and so can a function:


return 42;

return function() { return 42 }; 

Composing Functions
In functional programming, you’re always
looking for simple, repeatable actions to be
abstracted out into a function.
We can then build more complex features by
calling these functions in sequence
"Functional programming is the use of functions that
transform values into units of abstraction,
subsequently used to build software systems."
code examples
Give a 10% discount to all products of the chart above $30
Show the total value of products and discount
Imperative
Double valorTotal = 0d;
Double descontoTotal = 0d;
for (Produto produto : produtos) {
valorTotal += produto.getValor();
if (produto.getValor() > 30.00) {
descontoTotal += produto.getValor() * 0.1;
}
}
valorTotal -= descontoTotal;
functional
val valores = produtos map (_.valor)
val valorTotal = valores reduce
((total, valor) => total + valor)
val descontoTotal = valores filter
(_ > 30.00) map
(_ * 0.10) reduce
((total, desconto) => total + desconto)
val total = valorTotal - descontoTotal
code examples
Write a program to build a lyric sheet for
the song “99 bottles of beer"
X bottles of beer on the wall
X bottles of beer
Take one down, pass it around
X-1 bottles of beer on the wall
No more bottles of beer on the wall
Imperative
var lyrics = []; 

for (var bottles = 99; bottles > 0; bottles--) {
lyrics.push(bottles + " bottles of beer on the wall”);
lyrics.push(bottles + " bottles of beer");
lyrics.push("Take one down, pass it around");
if (bottles > 1) {

lyrics.push((bottles - 1) + " bottles of beer on the wall.");
} else { 

lyrics.push("No more bottles of beer on the wall!”);
}
}
functional
function lyricSegment(n) {
return _.chain([])
.push(n + " bottles of beer on the wall")
.push(n + " bottles of beer”)
.push("Take one down, pass it around")
.tap(function(lyrics) {
if (n > 1)

lyrics.push((n - 1) + " bottles of beer on the wall.");
else
lyrics.push("No more bottles of beer on the wall!");
})
.value();
}


functional
lyricSegment(9);
//=> ["9 bottles of beer on the wall",
// "9 bottles of beer",
// "Take one down, pass it around",
// "8 bottles of beer on the wall."]
functional
function song(start, end, lyricGen) {
return _.reduce(_.range(start,end,-1),
function(acc,n) {

return acc.concat(lyricGen(n));
}, []);
}
And using it is as simple as:
song(99, 0, lyricSegment);
//=> ["99 bottles of beer on the wall",
// ...
// "No more bottles of beer on the wall!"]
1. All of your functions must accept at least one argument.
2. All of your functions must return data or another function.
3. No loops
3 simple rules to avoid
imperative habits
conclusions
data abstractions
composing functions
declarative programming
concise code
Coursera: Functional Programming Principles in Scala
Book: Functional Javascript, Michael Fogus
http://www.smashingmagazine.com/2014/07/02/dont-be-scared-of-functional-
programming/
References
Thank you
@bruno_lui

More Related Content

What's hot

C Programming Language Part 7
C Programming Language Part 7C Programming Language Part 7
C Programming Language Part 7Rumman Ansari
 
C programming function
C  programming functionC  programming function
C programming functionargusacademy
 
Lessons learned from functional programming
Lessons learned from functional programmingLessons learned from functional programming
Lessons learned from functional programmingBryceLohr
 
Functions in c
Functions in cFunctions in c
Functions in cInnovative
 
Call by value
Call by valueCall by value
Call by valueDharani G
 
Call by value or call by reference in C++
Call by value or call by reference in C++Call by value or call by reference in C++
Call by value or call by reference in C++Sachin Yadav
 
parameter passing in c#
parameter passing in c#parameter passing in c#
parameter passing in c#khush_boo31
 
Pre defined Functions in C
Pre defined Functions in CPre defined Functions in C
Pre defined Functions in CPrabhu Govind
 
C Programming Language Part 6
C Programming Language Part 6C Programming Language Part 6
C Programming Language Part 6Rumman Ansari
 
How c program execute in c program
How c program execute in c program How c program execute in c program
How c program execute in c program Rumman Ansari
 
16717 functions in C++
16717 functions in C++16717 functions in C++
16717 functions in C++LPU
 

What's hot (19)

C Programming Language Part 7
C Programming Language Part 7C Programming Language Part 7
C Programming Language Part 7
 
C programming function
C  programming functionC  programming function
C programming function
 
Lessons learned from functional programming
Lessons learned from functional programmingLessons learned from functional programming
Lessons learned from functional programming
 
Functions in c
Functions in cFunctions in c
Functions in c
 
Call by value
Call by valueCall by value
Call by value
 
Call by value or call by reference in C++
Call by value or call by reference in C++Call by value or call by reference in C++
Call by value or call by reference in C++
 
parameter passing in c#
parameter passing in c#parameter passing in c#
parameter passing in c#
 
Functions in C
Functions in CFunctions in C
Functions in C
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
 
Function (rule in programming)
Function (rule in programming)Function (rule in programming)
Function (rule in programming)
 
Pre defined Functions in C
Pre defined Functions in CPre defined Functions in C
Pre defined Functions in C
 
functions of C++
functions of C++functions of C++
functions of C++
 
C Programming Language Part 6
C Programming Language Part 6C Programming Language Part 6
C Programming Language Part 6
 
C++ lecture 03
C++   lecture 03C++   lecture 03
C++ lecture 03
 
How c program execute in c program
How c program execute in c program How c program execute in c program
How c program execute in c program
 
C function presentation
C function presentationC function presentation
C function presentation
 
16717 functions in C++
16717 functions in C++16717 functions in C++
16717 functions in C++
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
 
Single row functions
Single row functionsSingle row functions
Single row functions
 

Similar to Functional Programming

Functional programming in JavaScript
Functional programming in JavaScriptFunctional programming in JavaScript
Functional programming in JavaScriptJoseph Smith
 
Programming Fundamentals Functions in C and types
Programming Fundamentals  Functions in C  and typesProgramming Fundamentals  Functions in C  and types
Programming Fundamentals Functions in C and typesimtiazalijoono
 
The Ring programming language version 1.9 book - Part 28 of 210
The Ring programming language version 1.9 book - Part 28 of 210The Ring programming language version 1.9 book - Part 28 of 210
The Ring programming language version 1.9 book - Part 28 of 210Mahmoud Samir Fayed
 
The Ring programming language version 1.5.1 book - Part 20 of 180
The Ring programming language version 1.5.1 book - Part 20 of 180The Ring programming language version 1.5.1 book - Part 20 of 180
The Ring programming language version 1.5.1 book - Part 20 of 180Mahmoud Samir Fayed
 
Chapter_1.__Functions_in_C++[1].pdf
Chapter_1.__Functions_in_C++[1].pdfChapter_1.__Functions_in_C++[1].pdf
Chapter_1.__Functions_in_C++[1].pdfTeshaleSiyum
 
Chapter 1. Functions in C++.pdf
Chapter 1.  Functions in C++.pdfChapter 1.  Functions in C++.pdf
Chapter 1. Functions in C++.pdfTeshaleSiyum
 
Fundamentals of functions in C program.pptx
Fundamentals of functions in C program.pptxFundamentals of functions in C program.pptx
Fundamentals of functions in C program.pptxChandrakantDivate1
 
The Ring programming language version 1.8 book - Part 26 of 202
The Ring programming language version 1.8 book - Part 26 of 202The Ring programming language version 1.8 book - Part 26 of 202
The Ring programming language version 1.8 book - Part 26 of 202Mahmoud Samir Fayed
 
VIT351 Software Development VI Unit1
VIT351 Software Development VI Unit1VIT351 Software Development VI Unit1
VIT351 Software Development VI Unit1YOGESH SINGH
 
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
 
Function in c program
Function in c programFunction in c program
Function in c programumesh patil
 

Similar to Functional Programming (20)

Functional programming in JavaScript
Functional programming in JavaScriptFunctional programming in JavaScript
Functional programming in JavaScript
 
Functions
FunctionsFunctions
Functions
 
Python_Functions.pdf
Python_Functions.pdfPython_Functions.pdf
Python_Functions.pdf
 
Programming Fundamentals Functions in C and types
Programming Fundamentals  Functions in C  and typesProgramming Fundamentals  Functions in C  and types
Programming Fundamentals Functions in C and types
 
Function
Function Function
Function
 
The Ring programming language version 1.9 book - Part 28 of 210
The Ring programming language version 1.9 book - Part 28 of 210The Ring programming language version 1.9 book - Part 28 of 210
The Ring programming language version 1.9 book - Part 28 of 210
 
The Ring programming language version 1.5.1 book - Part 20 of 180
The Ring programming language version 1.5.1 book - Part 20 of 180The Ring programming language version 1.5.1 book - Part 20 of 180
The Ring programming language version 1.5.1 book - Part 20 of 180
 
Chapter_1.__Functions_in_C++[1].pdf
Chapter_1.__Functions_in_C++[1].pdfChapter_1.__Functions_in_C++[1].pdf
Chapter_1.__Functions_in_C++[1].pdf
 
Chapter 1. Functions in C++.pdf
Chapter 1.  Functions in C++.pdfChapter 1.  Functions in C++.pdf
Chapter 1. Functions in C++.pdf
 
Fundamentals of functions in C program.pptx
Fundamentals of functions in C program.pptxFundamentals of functions in C program.pptx
Fundamentals of functions in C program.pptx
 
The Ring programming language version 1.8 book - Part 26 of 202
The Ring programming language version 1.8 book - Part 26 of 202The Ring programming language version 1.8 book - Part 26 of 202
The Ring programming language version 1.8 book - Part 26 of 202
 
VIT351 Software Development VI Unit1
VIT351 Software Development VI Unit1VIT351 Software Development VI Unit1
VIT351 Software Development VI Unit1
 
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
 
Advanced C - Part 2
Advanced C - Part 2Advanced C - Part 2
Advanced C - Part 2
 
Functions in c++
Functions in c++Functions in c++
Functions in c++
 
3. functions modules_programs (1)
3. functions modules_programs (1)3. functions modules_programs (1)
3. functions modules_programs (1)
 
Array Cont
Array ContArray Cont
Array Cont
 
4th unit full
4th unit full4th unit full
4th unit full
 
Function in c program
Function in c programFunction in c program
Function in c program
 
cp Module4(1)
cp Module4(1)cp Module4(1)
cp Module4(1)
 

More from Bruno Lui

Introdução ao Android
Introdução ao AndroidIntrodução ao Android
Introdução ao AndroidBruno Lui
 
Inversion of control
Inversion of controlInversion of control
Inversion of controlBruno Lui
 
Passionate programmer - Parte 1
Passionate programmer - Parte 1Passionate programmer - Parte 1
Passionate programmer - Parte 1Bruno Lui
 

More from Bruno Lui (6)

Switch
SwitchSwitch
Switch
 
Refactoring
RefactoringRefactoring
Refactoring
 
Introdução ao Android
Introdução ao AndroidIntrodução ao Android
Introdução ao Android
 
Inversion of control
Inversion of controlInversion of control
Inversion of control
 
Passionate programmer - Parte 1
Passionate programmer - Parte 1Passionate programmer - Parte 1
Passionate programmer - Parte 1
 
Clean Code
Clean CodeClean Code
Clean Code
 

Recently uploaded

How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?
How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?
How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?XfilesPro
 
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERRORTROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERRORTier1 app
 
Breaking the Code : A Guide to WhatsApp Business API.pdf
Breaking the Code : A Guide to WhatsApp Business API.pdfBreaking the Code : A Guide to WhatsApp Business API.pdf
Breaking the Code : A Guide to WhatsApp Business API.pdfMeon Technology
 
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoamOpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoamtakuyayamamoto1800
 
Using IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New ZealandUsing IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New ZealandIES VE
 
iGaming Platform & Lottery Solutions by Skilrock
iGaming Platform & Lottery Solutions by SkilrockiGaming Platform & Lottery Solutions by Skilrock
iGaming Platform & Lottery Solutions by SkilrockSkilrock Technologies
 
AI/ML Infra Meetup | ML explainability in Michelangelo
AI/ML Infra Meetup | ML explainability in MichelangeloAI/ML Infra Meetup | ML explainability in Michelangelo
AI/ML Infra Meetup | ML explainability in MichelangeloAlluxio, Inc.
 
A Comprehensive Appium Guide for Hybrid App Automation Testing.pdf
A Comprehensive Appium Guide for Hybrid App Automation Testing.pdfA Comprehensive Appium Guide for Hybrid App Automation Testing.pdf
A Comprehensive Appium Guide for Hybrid App Automation Testing.pdfkalichargn70th171
 
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...informapgpstrackings
 
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Shahin Sheidaei
 
Accelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with PlatformlessAccelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with PlatformlessWSO2
 
Advanced Flow Concepts Every Developer Should Know
Advanced Flow Concepts Every Developer Should KnowAdvanced Flow Concepts Every Developer Should Know
Advanced Flow Concepts Every Developer Should KnowPeter Caitens
 
Designing for Privacy in Amazon Web Services
Designing for Privacy in Amazon Web ServicesDesigning for Privacy in Amazon Web Services
Designing for Privacy in Amazon Web ServicesKrzysztofKkol1
 
Agnieszka Andrzejewska - BIM School Course in Kraków
Agnieszka Andrzejewska - BIM School Course in KrakówAgnieszka Andrzejewska - BIM School Course in Kraków
Agnieszka Andrzejewska - BIM School Course in Krakówbim.edu.pl
 
Studiovity film pre-production and screenwriting software
Studiovity film pre-production and screenwriting softwareStudiovity film pre-production and screenwriting software
Studiovity film pre-production and screenwriting softwareinfo611746
 
Facemoji Keyboard released its 2023 State of Emoji report, outlining the most...
Facemoji Keyboard released its 2023 State of Emoji report, outlining the most...Facemoji Keyboard released its 2023 State of Emoji report, outlining the most...
Facemoji Keyboard released its 2023 State of Emoji report, outlining the most...rajkumar669520
 
Crafting the Perfect Measurement Sheet with PLM Integration
Crafting the Perfect Measurement Sheet with PLM IntegrationCrafting the Perfect Measurement Sheet with PLM Integration
Crafting the Perfect Measurement Sheet with PLM IntegrationWave PLM
 
GraphAware - Transforming policing with graph-based intelligence analysis
GraphAware - Transforming policing with graph-based intelligence analysisGraphAware - Transforming policing with graph-based intelligence analysis
GraphAware - Transforming policing with graph-based intelligence analysisNeo4j
 
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBrokerSOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBrokerSOCRadar
 

Recently uploaded (20)

How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?
How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?
How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?
 
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERRORTROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
 
Breaking the Code : A Guide to WhatsApp Business API.pdf
Breaking the Code : A Guide to WhatsApp Business API.pdfBreaking the Code : A Guide to WhatsApp Business API.pdf
Breaking the Code : A Guide to WhatsApp Business API.pdf
 
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoamOpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
 
Using IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New ZealandUsing IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New Zealand
 
iGaming Platform & Lottery Solutions by Skilrock
iGaming Platform & Lottery Solutions by SkilrockiGaming Platform & Lottery Solutions by Skilrock
iGaming Platform & Lottery Solutions by Skilrock
 
AI/ML Infra Meetup | ML explainability in Michelangelo
AI/ML Infra Meetup | ML explainability in MichelangeloAI/ML Infra Meetup | ML explainability in Michelangelo
AI/ML Infra Meetup | ML explainability in Michelangelo
 
A Comprehensive Appium Guide for Hybrid App Automation Testing.pdf
A Comprehensive Appium Guide for Hybrid App Automation Testing.pdfA Comprehensive Appium Guide for Hybrid App Automation Testing.pdf
A Comprehensive Appium Guide for Hybrid App Automation Testing.pdf
 
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
 
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
 
Accelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with PlatformlessAccelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with Platformless
 
Advanced Flow Concepts Every Developer Should Know
Advanced Flow Concepts Every Developer Should KnowAdvanced Flow Concepts Every Developer Should Know
Advanced Flow Concepts Every Developer Should Know
 
Designing for Privacy in Amazon Web Services
Designing for Privacy in Amazon Web ServicesDesigning for Privacy in Amazon Web Services
Designing for Privacy in Amazon Web Services
 
Agnieszka Andrzejewska - BIM School Course in Kraków
Agnieszka Andrzejewska - BIM School Course in KrakówAgnieszka Andrzejewska - BIM School Course in Kraków
Agnieszka Andrzejewska - BIM School Course in Kraków
 
Studiovity film pre-production and screenwriting software
Studiovity film pre-production and screenwriting softwareStudiovity film pre-production and screenwriting software
Studiovity film pre-production and screenwriting software
 
Facemoji Keyboard released its 2023 State of Emoji report, outlining the most...
Facemoji Keyboard released its 2023 State of Emoji report, outlining the most...Facemoji Keyboard released its 2023 State of Emoji report, outlining the most...
Facemoji Keyboard released its 2023 State of Emoji report, outlining the most...
 
Crafting the Perfect Measurement Sheet with PLM Integration
Crafting the Perfect Measurement Sheet with PLM IntegrationCrafting the Perfect Measurement Sheet with PLM Integration
Crafting the Perfect Measurement Sheet with PLM Integration
 
Top Mobile App Development Companies 2024
Top Mobile App Development Companies 2024Top Mobile App Development Companies 2024
Top Mobile App Development Companies 2024
 
GraphAware - Transforming policing with graph-based intelligence analysis
GraphAware - Transforming policing with graph-based intelligence analysisGraphAware - Transforming policing with graph-based intelligence analysis
GraphAware - Transforming policing with graph-based intelligence analysis
 
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBrokerSOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBroker
 

Functional Programming

  • 3. modifying mutable variables using assignments and control structures such as if, then, else, lops, break, continue, return
  • 5. modifying mutable variables assignments programming without and other imperative control structures
  • 6. programming focusing on the functions functions ARE values that can be produced, consumed and composed
  • 8. Immutable Data Functional programs should be immutable, which means you would simply create new data structures instead of modifying ones that already exist.
  • 9. Referential transparency Functional programs should perform every task as if for the first time, with no knowledge of what may or may not have happened earlier in the program’s execution and without side effects.
  • 10. Function as first-class citizens functions can be defined anywhere they can be passed as parameters to functions and returned as results there exists a set of operators to compose functions
  • 11. • A number can be stored in a variable and so can a function: 
 var fortytwo = function() { return 42 }; • A number can be stored in an array slot and so can a function: 
 var fortytwos = [42, function() { return 42 }]; • A number can be stored in an object field and so can a function: 
 var fortytwos = {number: 42, fun: function() { return 42 }}; 
 • A number can be created as needed and so can a function: 
 42 + (function() { return 42 })(); //=> 84 • A number can be passed to a function and so can a function: 
 function weirdAdd(n, f) { return n + f() } weirdAdd(42, function() { return 42 }); 
 //=> 84 
 • A number can be returned from a function and so can a function: 
 return 42;
 return function() { return 42 }; 

  • 12. Composing Functions In functional programming, you’re always looking for simple, repeatable actions to be abstracted out into a function. We can then build more complex features by calling these functions in sequence
  • 13. "Functional programming is the use of functions that transform values into units of abstraction, subsequently used to build software systems."
  • 14. code examples Give a 10% discount to all products of the chart above $30 Show the total value of products and discount
  • 15. Imperative Double valorTotal = 0d; Double descontoTotal = 0d; for (Produto produto : produtos) { valorTotal += produto.getValor(); if (produto.getValor() > 30.00) { descontoTotal += produto.getValor() * 0.1; } } valorTotal -= descontoTotal;
  • 16. functional val valores = produtos map (_.valor) val valorTotal = valores reduce ((total, valor) => total + valor) val descontoTotal = valores filter (_ > 30.00) map (_ * 0.10) reduce ((total, desconto) => total + desconto) val total = valorTotal - descontoTotal
  • 17. code examples Write a program to build a lyric sheet for the song “99 bottles of beer" X bottles of beer on the wall X bottles of beer Take one down, pass it around X-1 bottles of beer on the wall No more bottles of beer on the wall
  • 18. Imperative var lyrics = []; 
 for (var bottles = 99; bottles > 0; bottles--) { lyrics.push(bottles + " bottles of beer on the wall”); lyrics.push(bottles + " bottles of beer"); lyrics.push("Take one down, pass it around"); if (bottles > 1) {
 lyrics.push((bottles - 1) + " bottles of beer on the wall."); } else { 
 lyrics.push("No more bottles of beer on the wall!”); } }
  • 19. functional function lyricSegment(n) { return _.chain([]) .push(n + " bottles of beer on the wall") .push(n + " bottles of beer”) .push("Take one down, pass it around") .tap(function(lyrics) { if (n > 1)
 lyrics.push((n - 1) + " bottles of beer on the wall."); else lyrics.push("No more bottles of beer on the wall!"); }) .value(); } 

  • 20. functional lyricSegment(9); //=> ["9 bottles of beer on the wall", // "9 bottles of beer", // "Take one down, pass it around", // "8 bottles of beer on the wall."]
  • 21. functional function song(start, end, lyricGen) { return _.reduce(_.range(start,end,-1), function(acc,n) {
 return acc.concat(lyricGen(n)); }, []); } And using it is as simple as: song(99, 0, lyricSegment); //=> ["99 bottles of beer on the wall", // ... // "No more bottles of beer on the wall!"]
  • 22. 1. All of your functions must accept at least one argument. 2. All of your functions must return data or another function. 3. No loops 3 simple rules to avoid imperative habits
  • 24. Coursera: Functional Programming Principles in Scala Book: Functional Javascript, Michael Fogus http://www.smashingmagazine.com/2014/07/02/dont-be-scared-of-functional- programming/ References