Created
July 23, 2016 14:38
-
-
Save JoolsF/de9412f5e7420508191dd5fb35f8d59e to your computer and use it in GitHub Desktop.
Partial function example 1
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
/** | |
* Partial Functions | |
* When a function is only defined for a specific input. | |
*/ | |
val between3and10: (String, Int) => Boolean = {case (_, num) => num >= 3 && num <= 10} | |
val wordFrequencies = ("habitual", 6) :: ("and", 56) :: ("consuetudinary", 2) :: | |
("additionally", 27) :: ("homely", 5) :: ("society", 13) :: Nil | |
wordFrequencies.filter{case (s,i) => between3and10(s,i) }.map(_._1) //res0: List[String] = List(habitual, homely) | |
/** | |
* In above example we filter then map remaining element. With PF we can reduce | |
* this and iterate over sequence only once thus saving CPU cycles and code length | |
* PartialFunction[-A, +B] type extends the type (A) => B (which can also be written | |
* as Function1[A, B]), and a pattern matching anonymous function is always of | |
* type PartialFunction. | |
* | |
* Due to this inheritance hierarchy, passing a pattern matching anonymous function to a | |
* method that expects a Function1, like map or filter, is perfectly fine, as long as that | |
* function is defined for all input values, i.e. there is always a matching case. | |
*/ | |
val pf: PartialFunction[(String, Int), String] = { | |
case (word, freq) if freq > 3 && freq < 10 => word | |
} | |
// Collect expects a partial function and knows how to with not matching inputs | |
wordFrequencies.collect(pf) // res1: List[String] = List(habitual, homely) | |
// Note, this is a more verbose way of defining PF by extending Partial Function trait | |
val pf2 = new PartialFunction[(String, Int), String] { | |
def apply(wordFrequency: (String, Int)) = wordFrequency match { | |
case (word, freq) if freq > 3 && freq < 25 => word | |
} | |
def isDefinedAt(wordFrequency: (String, Int)) = wordFrequency match { | |
case (word, freq) if freq > 3 && freq < 25 => true | |
case _ => false | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment