SlideShare a Scribd company logo
1 of 16
Download to read offline
Practical Scala
HOF
Who am I?
@raulraja
47deg.com
raulraja.com
Scala, Java, Objective-C
1. HOF Higher Order Functions
A function that takes a function as argument
or returns another function
e.g. map & filter
map transforms data
map sadness to happiness
:( :( :(

=> :) :) :)
map sadness to happiness - JAVA
public List<String> mapSadnessToHappiness (List<String> sadness) {
List<String> happiness = new ArrayList<String>(sadness.size());
for (int i = 0; i < sadness.size(); i++) {
String sadFace = sadness.get(i);
String happyFace = sadFace.replace('(', ')');
happiness.add(happyFace);
}
return happiness;
}
List<String> sadness = Arrays.asList(":(", ":(", ":(");
List<String> happiness = mapSadnessToHappiness(sadness);
map sadness to happiness - Scala
List(":(", ":(", ":(").map(face => face.replace('(', ')'))
map sadness to happiness - Scala
List(":(", ":(", ":(").map(_.replace('(', ')'))
filter remove the unwanted
filter sadness keeping happiness
:) :) :(

=> :) :)
filter sadness keeping happiness
List(":)", ":)", ":(").filter(_.contains(":)"))
Idiomatic Transformations
Count char occurrences on a String - JAVA
public static int countCharOccurrences(String haystack, char needle) {
int count = 0;
for (int i = 0; i < haystack.length(); i++) {
if (haystack.charAt(i) == needle) {
count++;
}
}
return count;
}
public static Map<Character, Integer> toCharOccurrenceMap(String haystack) {
Map<Character, Integer> map = new HashMap<Character, Integer>();
if (haystack != null) {
for (int i = 0; i < haystack.length(); i++) {
char character = haystack.charAt(i);
int count = countCharOccurrences(haystack, character);
map.put(character, count);
}
}
return map;
}
toCharOccurrenceMap("betabeers");
Idiomatic Transformations
Count char occurrences on a String
"betabeers" groupBy identity mapValues (_.size)
Key differentiator
Higher Order Functions help with most Collection problems
that you usually solve by looping over and manually creating
intermediate containers.
Transformed results stay immutable and thread safe.
No need to reinvent the wheel.
Code becomes readable and idiomatic
"betabeers" groupBy identity mapValues (_.size)
Other Powerful HOF’s examples
Sum
(1 to 1000).reduceLeft( _ + _ )
(1 to 1000).sum

Partition filter
val (passed, failed) = List(49, 58, 88, 90) partition ( _ > 60 )

min
List(14, 35, -7, 46, 98).min

max
List(14, 35, -7, 46, 98).max

Imperative iteration
(1 to 10) foreach (println)

Parallel Collections
(1 to 10).par foreach(_ => println(Thread.currentThread.getName))
Become a Scala Master
For comprehensions
Case Classes
Futures
Options
Traits
Either
Pattern Matching
Monads
Actors
DSL’s
...

More Related Content

What's hot

What's hot (20)

Streams and lambdas the good, the bad and the ugly
Streams and lambdas the good, the bad and the uglyStreams and lambdas the good, the bad and the ugly
Streams and lambdas the good, the bad and the ugly
 
IGraph a tool to analyze your network
IGraph a tool to analyze your networkIGraph a tool to analyze your network
IGraph a tool to analyze your network
 
Map, Reduce and Filter in Swift
Map, Reduce and Filter in SwiftMap, Reduce and Filter in Swift
Map, Reduce and Filter in Swift
 
Lec4
Lec4Lec4
Lec4
 
C++ ARRAY WITH EXAMPLES
C++ ARRAY WITH EXAMPLESC++ ARRAY WITH EXAMPLES
C++ ARRAY WITH EXAMPLES
 
Cypher.PL: Executable Specification of Cypher written in Prolog
Cypher.PL: Executable Specification of Cypher written in PrologCypher.PL: Executable Specification of Cypher written in Prolog
Cypher.PL: Executable Specification of Cypher written in Prolog
 
Arrays
ArraysArrays
Arrays
 
18 hashing
18 hashing18 hashing
18 hashing
 
Scala parallel-collections
Scala parallel-collectionsScala parallel-collections
Scala parallel-collections
 
Hashing notes data structures (HASHING AND HASH FUNCTIONS)
Hashing notes data structures (HASHING AND HASH FUNCTIONS)Hashing notes data structures (HASHING AND HASH FUNCTIONS)
Hashing notes data structures (HASHING AND HASH FUNCTIONS)
 
2- Dimensional Arrays
2- Dimensional Arrays2- Dimensional Arrays
2- Dimensional Arrays
 
Functional programming in Swift
Functional programming in SwiftFunctional programming in Swift
Functional programming in Swift
 
Pandas pythonfordatascience
Pandas pythonfordatasciencePandas pythonfordatascience
Pandas pythonfordatascience
 
Arrays
ArraysArrays
Arrays
 
XKE Typeclass
XKE TypeclassXKE Typeclass
XKE Typeclass
 
MEngine Overview
MEngine OverviewMEngine Overview
MEngine Overview
 
Arrays in c
Arrays in cArrays in c
Arrays in c
 
Functional programming with_scala
Functional programming with_scalaFunctional programming with_scala
Functional programming with_scala
 
Arrays
ArraysArrays
Arrays
 
Tools for research plotting
Tools for research plottingTools for research plotting
Tools for research plotting
 

Similar to Scala Higher Order Functions

JBUG 11 - Scala For Java Programmers
JBUG 11 - Scala For Java ProgrammersJBUG 11 - Scala For Java Programmers
JBUG 11 - Scala For Java ProgrammersTikal Knowledge
 
LeetCode April Coding Challenge
LeetCode April Coding ChallengeLeetCode April Coding Challenge
LeetCode April Coding ChallengeSunil Yadav
 
Scalding - Hadoop Word Count in LESS than 70 lines of code
Scalding - Hadoop Word Count in LESS than 70 lines of codeScalding - Hadoop Word Count in LESS than 70 lines of code
Scalding - Hadoop Word Count in LESS than 70 lines of codeKonrad Malawski
 
Introduction to Perl
Introduction to PerlIntroduction to Perl
Introduction to PerlSway Wang
 
  package Chapter_20;import ToolKit.PostfixNotation;import javaf.pdf
  package Chapter_20;import ToolKit.PostfixNotation;import javaf.pdf  package Chapter_20;import ToolKit.PostfixNotation;import javaf.pdf
  package Chapter_20;import ToolKit.PostfixNotation;import javaf.pdfsudhirchourasia86
 
Hashing in datastructure
Hashing in datastructureHashing in datastructure
Hashing in datastructurerajshreemuthiah
 
18. Dictionaries, Hash-Tables and Set
18. Dictionaries, Hash-Tables and Set18. Dictionaries, Hash-Tables and Set
18. Dictionaries, Hash-Tables and SetIntro C# Book
 
Implementing virtual machines in go & c 2018 redux
Implementing virtual machines in go & c 2018 reduxImplementing virtual machines in go & c 2018 redux
Implementing virtual machines in go & c 2018 reduxEleanor McHugh
 
Radix and shell sort
Radix and shell sortRadix and shell sort
Radix and shell sortAaron Joaquin
 
Hitchhiker's Guide to Functional Programming
Hitchhiker's Guide to Functional ProgrammingHitchhiker's Guide to Functional Programming
Hitchhiker's Guide to Functional ProgrammingSergey Shishkin
 
Better d3 charts with tdd
Better d3 charts with tddBetter d3 charts with tdd
Better d3 charts with tddMarcos Iglesias
 
Google Guava for cleaner code
Google Guava for cleaner codeGoogle Guava for cleaner code
Google Guava for cleaner codeMite Mitreski
 
Refactoring to Macros with Clojure
Refactoring to Macros with ClojureRefactoring to Macros with Clojure
Refactoring to Macros with ClojureDmitry Buzdin
 
Monadologie
MonadologieMonadologie
Monadologieleague
 
Kotlin, Spek and tests
Kotlin, Spek and testsKotlin, Spek and tests
Kotlin, Spek and testsintive
 
How Hashmap works internally in java
How Hashmap works internally  in javaHow Hashmap works internally  in java
How Hashmap works internally in javaRamakrishna Joshi
 

Similar to Scala Higher Order Functions (20)

Scala @ TomTom
Scala @ TomTomScala @ TomTom
Scala @ TomTom
 
JBUG 11 - Scala For Java Programmers
JBUG 11 - Scala For Java ProgrammersJBUG 11 - Scala For Java Programmers
JBUG 11 - Scala For Java Programmers
 
Internal workshop es6_2015
Internal workshop es6_2015Internal workshop es6_2015
Internal workshop es6_2015
 
LeetCode April Coding Challenge
LeetCode April Coding ChallengeLeetCode April Coding Challenge
LeetCode April Coding Challenge
 
4.4 hashing02
4.4 hashing024.4 hashing02
4.4 hashing02
 
Scalding - Hadoop Word Count in LESS than 70 lines of code
Scalding - Hadoop Word Count in LESS than 70 lines of codeScalding - Hadoop Word Count in LESS than 70 lines of code
Scalding - Hadoop Word Count in LESS than 70 lines of code
 
Introduction to Perl
Introduction to PerlIntroduction to Perl
Introduction to Perl
 
  package Chapter_20;import ToolKit.PostfixNotation;import javaf.pdf
  package Chapter_20;import ToolKit.PostfixNotation;import javaf.pdf  package Chapter_20;import ToolKit.PostfixNotation;import javaf.pdf
  package Chapter_20;import ToolKit.PostfixNotation;import javaf.pdf
 
Hashing in datastructure
Hashing in datastructureHashing in datastructure
Hashing in datastructure
 
18. Dictionaries, Hash-Tables and Set
18. Dictionaries, Hash-Tables and Set18. Dictionaries, Hash-Tables and Set
18. Dictionaries, Hash-Tables and Set
 
Implementing virtual machines in go & c 2018 redux
Implementing virtual machines in go & c 2018 reduxImplementing virtual machines in go & c 2018 redux
Implementing virtual machines in go & c 2018 redux
 
Radix and shell sort
Radix and shell sortRadix and shell sort
Radix and shell sort
 
Hitchhiker's Guide to Functional Programming
Hitchhiker's Guide to Functional ProgrammingHitchhiker's Guide to Functional Programming
Hitchhiker's Guide to Functional Programming
 
Arrays
ArraysArrays
Arrays
 
Better d3 charts with tdd
Better d3 charts with tddBetter d3 charts with tdd
Better d3 charts with tdd
 
Google Guava for cleaner code
Google Guava for cleaner codeGoogle Guava for cleaner code
Google Guava for cleaner code
 
Refactoring to Macros with Clojure
Refactoring to Macros with ClojureRefactoring to Macros with Clojure
Refactoring to Macros with Clojure
 
Monadologie
MonadologieMonadologie
Monadologie
 
Kotlin, Spek and tests
Kotlin, Spek and testsKotlin, Spek and tests
Kotlin, Spek and tests
 
How Hashmap works internally in java
How Hashmap works internally  in javaHow Hashmap works internally  in java
How Hashmap works internally in java
 

Recently uploaded

Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your BudgetHyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your BudgetEnjoy Anytime
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptxLBM Solutions
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxMaking_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxnull - The Open Security Community
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?XfilesPro
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAndikSusilo4
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 

Recently uploaded (20)

Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your BudgetHyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptx
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxMaking_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & Application
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 

Scala Higher Order Functions

  • 3. 1. HOF Higher Order Functions A function that takes a function as argument or returns another function e.g. map & filter
  • 5. map sadness to happiness :( :( :( => :) :) :)
  • 6. map sadness to happiness - JAVA public List<String> mapSadnessToHappiness (List<String> sadness) { List<String> happiness = new ArrayList<String>(sadness.size()); for (int i = 0; i < sadness.size(); i++) { String sadFace = sadness.get(i); String happyFace = sadFace.replace('(', ')'); happiness.add(happyFace); } return happiness; } List<String> sadness = Arrays.asList(":(", ":(", ":("); List<String> happiness = mapSadnessToHappiness(sadness);
  • 7. map sadness to happiness - Scala List(":(", ":(", ":(").map(face => face.replace('(', ')'))
  • 8. map sadness to happiness - Scala List(":(", ":(", ":(").map(_.replace('(', ')'))
  • 10. filter sadness keeping happiness :) :) :( => :) :)
  • 11. filter sadness keeping happiness List(":)", ":)", ":(").filter(_.contains(":)"))
  • 12. Idiomatic Transformations Count char occurrences on a String - JAVA public static int countCharOccurrences(String haystack, char needle) { int count = 0; for (int i = 0; i < haystack.length(); i++) { if (haystack.charAt(i) == needle) { count++; } } return count; } public static Map<Character, Integer> toCharOccurrenceMap(String haystack) { Map<Character, Integer> map = new HashMap<Character, Integer>(); if (haystack != null) { for (int i = 0; i < haystack.length(); i++) { char character = haystack.charAt(i); int count = countCharOccurrences(haystack, character); map.put(character, count); } } return map; } toCharOccurrenceMap("betabeers");
  • 13. Idiomatic Transformations Count char occurrences on a String "betabeers" groupBy identity mapValues (_.size)
  • 14. Key differentiator Higher Order Functions help with most Collection problems that you usually solve by looping over and manually creating intermediate containers. Transformed results stay immutable and thread safe. No need to reinvent the wheel. Code becomes readable and idiomatic "betabeers" groupBy identity mapValues (_.size)
  • 15. Other Powerful HOF’s examples Sum (1 to 1000).reduceLeft( _ + _ ) (1 to 1000).sum Partition filter val (passed, failed) = List(49, 58, 88, 90) partition ( _ > 60 ) min List(14, 35, -7, 46, 98).min max List(14, 35, -7, 46, 98).max Imperative iteration (1 to 10) foreach (println) Parallel Collections (1 to 10).par foreach(_ => println(Thread.currentThread.getName))
  • 16. Become a Scala Master For comprehensions Case Classes Futures Options Traits Either Pattern Matching Monads Actors DSL’s ...