SlideShare a Scribd company logo
1 of 29
Download to read offline
Functional Programming
Contact me: hadoope@gmail.com
Let’s Rock!
Why FP ???
Single Threading can’t scale,
but multi-ple threading is hard!
Simple is Beautiful!
Beautiful Concurrency ???
Thread Safe
Synchronized
Deadlock
Livelock
Races
Debugging
Mutable shared state!!!
Functional Programming
No Mutable
In computer science, functional programming is a programming paradigm,
a style of building the structure and elements of computer programs,
that treats computation as the evaluation of mathematical functions and
avoids state and mutable data.
First Class Function
Higher-Order Function
Purify
Curry
Lazy Evaluation
Monoid
Monad
Tail Recursive
First Class Function
http://jsfiddle.net/hadoope/RAYy7/
Number Versus Function
Higher-Order Function
Functions that take other functions
Functions that return other functions
var people = [{name: "Fred", age: 65}, {name: "Lucy", age: 36}];
_.max(people, function(p) { return p.age });
function always(VALUE) {
return function() {
return VALUE;
};
};
Currying
Currying using Lambda calculus
(x, y) -> x * x + y *y
x -> y -> x * x + y *y
=
Currying in JavaScript
function curry3(fun) {
return function(last) {
return function(middle) {
return function(first) {
return fun(first, middle, last);
};
};
};
};
function no_curry(fun, last, middle, first){
return fun(last, middle, first);
}
Define a Method
Define a Method in
Currying Way
Recursion and Tail Recursive
def factorial(n)
if (n == 1)
return 1
else
return n* factorial(n-1)
end
end
@tailrec def factorial(acc: Int, n:Int ) = {
if (n <= 1) acc
else factorial( n * acc, n - 1)
}
Lazy Evaluation
In programming language theory, lazy evaluation, or call-by-need is an evaluation strategy
which delays the evaluation of an expression until its value is needed (non-strict evaluation)
and which also avoids repeated evaluations (sharing).
Lazy Evaluation
 Performance increases by avoiding needless calculations, and error conditions in
evaluating compound expressions
 The ability to construct potentially infinite data structures.
 The ability to define control flow (structures) as abstractions instead of primitives
Pattern Matching
• Object Matching
Import scala.util.Random
var randomInt = new Random().nextInt(10)
randomInt match {
case 7 => println(“lucky seven”)
case otherNumber => println( “get” + otherNumber)
}
Pattern Matching
• Type Matching
var items = List(1, “foo”, 3.5)
for (item <- items) {
item match {
case i: Int => println(“got an Integer: ” + i)
case s: String => println(“got a String: ” + s)
case d: Double => println(“got a double: ” + d)
case other => println(“got others” + other)
}
}
Pattern Matching
Functionalpolymorphism
Versus
OOpolymorphism
Monoid
Just what is a monoid, then? It is simply an implementation of an interface
governed by some laws. Stated tersely, a monoid is a type together with an
associative binary operation (op) which has an identity element (zero).
trait Monoid[A] {
def op(a1: A, a2: A): A
def zero: A
}
def listMonoid[A] = new Monoid[List[A]] {
def op(a1: List[A], a2: List[A]) = a1 ++ a2
def zero = Nil
}
Monoid will buy us ???
Associativity brings high parallelism
op(a, op(b, op(c,d)))Folding to the right:
After folding in parallel: op( op(a,b), op(c,d))
op(op(op(a, b), c), d)Folding to the right:
Monad
In functional programming, a monad is a structure that
represents computations defined as sequences of steps. A type with a monad
structure defines what it means to
chain operations, or nest functions of that type together. This allows the programmer
to build pipelines that process data in steps, in which each action is decorated with
additional processing rules provided by the monad.
Functional Javascript
• Collection-Centric Programming
Functional Javascript
• Collection-Centric Programming (map, reduce
and filter)
http://jsfiddle.net/hadoope/xhQ4P/
Monad using Javascript
var stack = [];
stack.push(4);
stack.push(5);
stack.pop(); // 5
stack.pop(); // 4
Normal Style
http://igstan.ro/posts/2011-05-02-understanding-monads-with-javascript.html
Monad using Javascript
http://jsfiddle.net/hadoope/FcD5S/
Continuation-Passing Style
Monad using Javascript
• Currying push and pop
http://jsfiddle.net/hadoope/62bfe/2/
Monad using Javascript
• Preparing bind to Handle Intermediate Stacks
http://jsfiddle.net/hadoope/Lsgw5/
Monad Using Haskell
computation = push 4 >>= _ ->
push 5 >>= _ ->
pop >> a ->
pop >>= b->
return $ (show a) ++ “ : ” ++ (show b)
Computation = do push 4
push 5
a <- pop
b <- pop
return $ (show a) ++ “ : “ ++ (show b)
https://www.coursera.org/course/progfun
Thank You
29

More Related Content

What's hot (20)

Chapter 7: Queue data structure
Chapter 7:  Queue data structureChapter 7:  Queue data structure
Chapter 7: Queue data structure
 
Chapter 4: basic search algorithms data structure
Chapter 4: basic search algorithms data structureChapter 4: basic search algorithms data structure
Chapter 4: basic search algorithms data structure
 
List
ListList
List
 
Stack of Data structure
Stack of Data structureStack of Data structure
Stack of Data structure
 
Chapter 5: linked list data structure
Chapter 5: linked list data structureChapter 5: linked list data structure
Chapter 5: linked list data structure
 
Algorithms: II
Algorithms: IIAlgorithms: II
Algorithms: II
 
02 Stack
02 Stack02 Stack
02 Stack
 
String predefined functions in C programming
String predefined functions in C  programmingString predefined functions in C  programming
String predefined functions in C programming
 
Scilab
Scilab Scilab
Scilab
 
Stack and queue
Stack and queueStack and queue
Stack and queue
 
Queue-Data Structure
Queue-Data StructureQueue-Data Structure
Queue-Data Structure
 
multiple linear regression
multiple linear regressionmultiple linear regression
multiple linear regression
 
Stack
StackStack
Stack
 
Queue
QueueQueue
Queue
 
Queue Data Structure
Queue Data StructureQueue Data Structure
Queue Data Structure
 
Array within a class
Array within a classArray within a class
Array within a class
 
R: Apply Functions
R: Apply FunctionsR: Apply Functions
R: Apply Functions
 
Queue
QueueQueue
Queue
 
Data Structure (Queue)
Data Structure (Queue)Data Structure (Queue)
Data Structure (Queue)
 
Data structure stack&queue basics
Data structure stack&queue   basicsData structure stack&queue   basics
Data structure stack&queue basics
 

Similar to Functional Programming

Yin Yangs of Software Development
Yin Yangs of Software DevelopmentYin Yangs of Software Development
Yin Yangs of Software DevelopmentNaveenkumar Muguda
 
An Overview Of Python With Functional Programming
An Overview Of Python With Functional ProgrammingAn Overview Of Python With Functional Programming
An Overview Of Python With Functional ProgrammingAdam Getchell
 
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
 
Pydiomatic
PydiomaticPydiomatic
Pydiomaticrik0
 
Twins: Object Oriented Programming and Functional Programming
Twins: Object Oriented Programming and Functional ProgrammingTwins: Object Oriented Programming and Functional Programming
Twins: Object Oriented Programming and Functional ProgrammingRichardWarburton
 
Functional Programming With Scala
Functional Programming With ScalaFunctional Programming With Scala
Functional Programming With ScalaKnoldus Inc.
 
The Fuss about || Haskell | Scala | F# ||
The Fuss about || Haskell | Scala | F# ||The Fuss about || Haskell | Scala | F# ||
The Fuss about || Haskell | Scala | F# ||Ashwin Rao
 
Functional programming with Scala
Functional programming with ScalaFunctional programming with Scala
Functional programming with ScalaNeelkanth Sachdeva
 
Concepts In Object Oriented Programming Languages
Concepts In Object Oriented Programming LanguagesConcepts In Object Oriented Programming Languages
Concepts In Object Oriented Programming Languagesppd1961
 
JS Responsibilities
JS ResponsibilitiesJS Responsibilities
JS ResponsibilitiesBrendan Eich
 
Scala clojure techday_2011
Scala clojure techday_2011Scala clojure techday_2011
Scala clojure techday_2011Thadeu Russo
 
Scala for Java Programmers
Scala for Java ProgrammersScala for Java Programmers
Scala for Java ProgrammersEric Pederson
 
Standardizing on a single N-dimensional array API for Python
Standardizing on a single N-dimensional array API for PythonStandardizing on a single N-dimensional array API for Python
Standardizing on a single N-dimensional array API for PythonRalf Gommers
 
conceptsinobjectorientedprogramminglanguages-12659959597745-phpapp02.pdf
conceptsinobjectorientedprogramminglanguages-12659959597745-phpapp02.pdfconceptsinobjectorientedprogramminglanguages-12659959597745-phpapp02.pdf
conceptsinobjectorientedprogramminglanguages-12659959597745-phpapp02.pdfSahajShrimal1
 
Fuel Up JavaScript with Functional Programming
Fuel Up JavaScript with Functional ProgrammingFuel Up JavaScript with Functional Programming
Fuel Up JavaScript with Functional ProgrammingShine Xavier
 

Similar to Functional Programming (20)

Functional programming in C++
Functional programming in C++Functional programming in C++
Functional programming in C++
 
Yin Yangs of Software Development
Yin Yangs of Software DevelopmentYin Yangs of Software Development
Yin Yangs of Software Development
 
An Overview Of Python With Functional Programming
An Overview Of Python With Functional ProgrammingAn Overview Of Python With Functional Programming
An Overview Of Python With Functional Programming
 
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
 
Scala ntnu
Scala ntnuScala ntnu
Scala ntnu
 
Pydiomatic
PydiomaticPydiomatic
Pydiomatic
 
Python idiomatico
Python idiomaticoPython idiomatico
Python idiomatico
 
Twins: Object Oriented Programming and Functional Programming
Twins: Object Oriented Programming and Functional ProgrammingTwins: Object Oriented Programming and Functional Programming
Twins: Object Oriented Programming and Functional Programming
 
Functional Programming With Scala
Functional Programming With ScalaFunctional Programming With Scala
Functional Programming With Scala
 
The Fuss about || Haskell | Scala | F# ||
The Fuss about || Haskell | Scala | F# ||The Fuss about || Haskell | Scala | F# ||
The Fuss about || Haskell | Scala | F# ||
 
Functional programming with Scala
Functional programming with ScalaFunctional programming with Scala
Functional programming with Scala
 
Pune Clojure Course Outline
Pune Clojure Course OutlinePune Clojure Course Outline
Pune Clojure Course Outline
 
Concepts In Object Oriented Programming Languages
Concepts In Object Oriented Programming LanguagesConcepts In Object Oriented Programming Languages
Concepts In Object Oriented Programming Languages
 
JS Responsibilities
JS ResponsibilitiesJS Responsibilities
JS Responsibilities
 
Scala clojure techday_2011
Scala clojure techday_2011Scala clojure techday_2011
Scala clojure techday_2011
 
Scala for Java Programmers
Scala for Java ProgrammersScala for Java Programmers
Scala for Java Programmers
 
Functional programming 101
Functional programming 101Functional programming 101
Functional programming 101
 
Standardizing on a single N-dimensional array API for Python
Standardizing on a single N-dimensional array API for PythonStandardizing on a single N-dimensional array API for Python
Standardizing on a single N-dimensional array API for Python
 
conceptsinobjectorientedprogramminglanguages-12659959597745-phpapp02.pdf
conceptsinobjectorientedprogramminglanguages-12659959597745-phpapp02.pdfconceptsinobjectorientedprogramminglanguages-12659959597745-phpapp02.pdf
conceptsinobjectorientedprogramminglanguages-12659959597745-phpapp02.pdf
 
Fuel Up JavaScript with Functional Programming
Fuel Up JavaScript with Functional ProgrammingFuel Up JavaScript with Functional Programming
Fuel Up JavaScript with Functional Programming
 

Recently uploaded

Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Zilliz
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWERMadyBayot
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdflior mazor
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
A Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusA Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusZilliz
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDropbox
 
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...apidays
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 

Recently uploaded (20)

Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
A Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusA Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source Milvus
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 

Functional Programming

  • 1. Functional Programming Contact me: hadoope@gmail.com Let’s Rock!
  • 2. Why FP ??? Single Threading can’t scale, but multi-ple threading is hard! Simple is Beautiful!
  • 3. Beautiful Concurrency ??? Thread Safe Synchronized Deadlock Livelock Races Debugging Mutable shared state!!!
  • 5. In computer science, functional programming is a programming paradigm, a style of building the structure and elements of computer programs, that treats computation as the evaluation of mathematical functions and avoids state and mutable data.
  • 6. First Class Function Higher-Order Function Purify Curry Lazy Evaluation Monoid Monad Tail Recursive
  • 8. Higher-Order Function Functions that take other functions Functions that return other functions var people = [{name: "Fred", age: 65}, {name: "Lucy", age: 36}]; _.max(people, function(p) { return p.age }); function always(VALUE) { return function() { return VALUE; }; };
  • 10. Currying using Lambda calculus (x, y) -> x * x + y *y x -> y -> x * x + y *y =
  • 11. Currying in JavaScript function curry3(fun) { return function(last) { return function(middle) { return function(first) { return fun(first, middle, last); }; }; }; }; function no_curry(fun, last, middle, first){ return fun(last, middle, first); } Define a Method Define a Method in Currying Way
  • 12. Recursion and Tail Recursive def factorial(n) if (n == 1) return 1 else return n* factorial(n-1) end end @tailrec def factorial(acc: Int, n:Int ) = { if (n <= 1) acc else factorial( n * acc, n - 1) }
  • 13. Lazy Evaluation In programming language theory, lazy evaluation, or call-by-need is an evaluation strategy which delays the evaluation of an expression until its value is needed (non-strict evaluation) and which also avoids repeated evaluations (sharing).
  • 14. Lazy Evaluation  Performance increases by avoiding needless calculations, and error conditions in evaluating compound expressions  The ability to construct potentially infinite data structures.  The ability to define control flow (structures) as abstractions instead of primitives
  • 15. Pattern Matching • Object Matching Import scala.util.Random var randomInt = new Random().nextInt(10) randomInt match { case 7 => println(“lucky seven”) case otherNumber => println( “get” + otherNumber) }
  • 16. Pattern Matching • Type Matching var items = List(1, “foo”, 3.5) for (item <- items) { item match { case i: Int => println(“got an Integer: ” + i) case s: String => println(“got a String: ” + s) case d: Double => println(“got a double: ” + d) case other => println(“got others” + other) } }
  • 18. Monoid Just what is a monoid, then? It is simply an implementation of an interface governed by some laws. Stated tersely, a monoid is a type together with an associative binary operation (op) which has an identity element (zero). trait Monoid[A] { def op(a1: A, a2: A): A def zero: A } def listMonoid[A] = new Monoid[List[A]] { def op(a1: List[A], a2: List[A]) = a1 ++ a2 def zero = Nil }
  • 19. Monoid will buy us ??? Associativity brings high parallelism op(a, op(b, op(c,d)))Folding to the right: After folding in parallel: op( op(a,b), op(c,d)) op(op(op(a, b), c), d)Folding to the right:
  • 20. Monad In functional programming, a monad is a structure that represents computations defined as sequences of steps. A type with a monad structure defines what it means to chain operations, or nest functions of that type together. This allows the programmer to build pipelines that process data in steps, in which each action is decorated with additional processing rules provided by the monad.
  • 22. Functional Javascript • Collection-Centric Programming (map, reduce and filter) http://jsfiddle.net/hadoope/xhQ4P/
  • 23. Monad using Javascript var stack = []; stack.push(4); stack.push(5); stack.pop(); // 5 stack.pop(); // 4 Normal Style http://igstan.ro/posts/2011-05-02-understanding-monads-with-javascript.html
  • 25. Monad using Javascript • Currying push and pop http://jsfiddle.net/hadoope/62bfe/2/
  • 26. Monad using Javascript • Preparing bind to Handle Intermediate Stacks http://jsfiddle.net/hadoope/Lsgw5/
  • 27. Monad Using Haskell computation = push 4 >>= _ -> push 5 >>= _ -> pop >> a -> pop >>= b-> return $ (show a) ++ “ : ” ++ (show b) Computation = do push 4 push 5 a <- pop b <- pop return $ (show a) ++ “ : “ ++ (show b)