Skip to content

Instantly share code, notes, and snippets.

@4fuss
Last active August 29, 2015 13:56
Show Gist options
  • Save 4fuss/8803925 to your computer and use it in GitHub Desktop.
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.
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