500

# Practical Scala - Higher Order Functions

A basic intro to HOF's for Scala newcomers, Part of the Betabeers series

July 26, 2013

## Transcript

3. ### 1. HOF Higher Order Functions A function that takes a

function as argument or returns another function e.g. map & ﬁlter

:)

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

face.replace('(', ')'))

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