Last active
August 29, 2015 13:56
-
-
Save 4fuss/8803925 to your computer and use it in GitHub Desktop.
Example of using partial functions in collect doing filtering and mapping in one interation over a sequence.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
val wordFrequencies = ("habitaul", 6) :: ("and", 56) :: ("consuetudinary", 2) :: ("additionally", 27) :: ("homely", 5) :: ("society", 13) :: Nil | |
//verbose implementation - two iterations one for filter and one for map | |
def wordsWithoutOutliers(wordFrequencies: Seq[(String, Int)]): Seq[String] = | |
wordFrequencies.filter{case (w, f) => f > 3 && f <25}.map{ case (w,f) => w } | |
//defining partial function using anonymous function pattern matching | |
val pf: PartialFunction[(String, Int), String] = { | |
case (word, freq) if freq > 3 && freq < 25 => word | |
} | |
wordFrequencies.collect(pf) | |
wordFrequencies.collect{case (word, freq) if freq > 3 && freq < 25 => word} //same as above |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment