Slide 1

Slide 1 text

Practical Scala HOF

Slide 2

Slide 2 text

Who am I? @raulraja 47deg.com raulraja.com Scala, Java, Objective-C

Slide 3

Slide 3 text

1. HOF Higher Order Functions A function that takes a function as argument or returns another function e.g. map & filter

Slide 4

Slide 4 text

map transforms data

Slide 5

Slide 5 text

map sadness to happiness :( :( :( => :) :) :)

Slide 6

Slide 6 text

map sadness to happiness - JAVA public List mapSadnessToHappiness (List sadness) { List happiness = new ArrayList(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 sadness = Arrays.asList(":(", ":(", ":("); List happiness = mapSadnessToHappiness(sadness);

Slide 7

Slide 7 text

map sadness to happiness - Scala List(":(", ":(", ":(").map(face => face.replace('(', ')'))

Slide 8

Slide 8 text

map sadness to happiness - Scala List(":(", ":(", ":(").map(_.replace('(', ')'))

Slide 9

Slide 9 text

filter remove the unwanted

Slide 10

Slide 10 text

filter sadness keeping happiness :) :) :( => :) :)

Slide 11

Slide 11 text

filter sadness keeping happiness List(":)", ":)", ":(").filter(_.contains(":)"))

Slide 12

Slide 12 text

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 toCharOccurrenceMap(String haystack) { Map map = new HashMap(); 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");

Slide 13

Slide 13 text

Idiomatic Transformations Count char occurrences on a String "betabeers" groupBy identity mapValues (_.size)

Slide 14

Slide 14 text

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)

Slide 15

Slide 15 text

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

Slide 16

Slide 16 text

Become a Scala Master For comprehensions Case Classes Futures Options Traits Either Pattern Matching Monads Actors DSL’s ...