scala higher order functions
DESCRIPTION
A basic intro to HOF's for Scala newcomers, Part of the Betabeers seriesTRANSCRIPT
Practical ScalaHOF
Who am [email protected]
Scala, Java, Objective-C
1. HOF Higher Order FunctionsA function that takes a function as argument
or returns another functione.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 TransformationsCount 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 TransformationsCount char occurrences on a String
"betabeers" groupBy identity mapValues (_.size)
Key differentiatorHigher 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 filterval (passed, failed) = List(49, 58, 88, 90) partition ( _ > 60 )
minList(14, 35, -7, 46, 98).min
maxList(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 comprehensionsCase Classes
FuturesOptionsTraitsEither
Pattern MatchingMonadsActorsDSL’s
...