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

Introduction to Perl
Introduction to PerlIntroduction to Perl
Introduction to Perl
Sway 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.pdf
sudhirchourasia86
 
Refactoring to Macros with Clojure
Refactoring to Macros with ClojureRefactoring to Macros with Clojure
Refactoring to Macros with Clojure
Dmitry Buzdin
 

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

Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Victor Rentea
 
+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...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 

Recently uploaded (20)

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
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
AI in Action: Real World Use Cases by Anitaraj
AI in Action: Real World Use Cases by AnitarajAI in Action: Real World Use Cases by Anitaraj
AI in Action: Real World Use Cases by Anitaraj
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
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
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
+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...
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
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
 
Introduction to use of FHIR Documents in ABDM
Introduction to use of FHIR Documents in ABDMIntroduction to use of FHIR Documents in ABDM
Introduction to use of FHIR Documents in ABDM
 

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 ...