Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Practical Scala - Higher Order Functions

Practical Scala - Higher Order Functions

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

Raúl Raja Martínez

July 26, 2013
Tweet

More Decks by Raúl Raja Martínez

Other Decks in Programming

Transcript

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

    function as argument or returns another function e.g. map & filter
  2. 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);
  3. 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");
  4. 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)
  5. 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))
  6. Become a Scala Master For comprehensions Case Classes Futures Options

    Traits Either Pattern Matching Monads Actors DSL’s ...