Created
May 14, 2013 10:50
-
-
Save kiritsuku/5575119 to your computer and use it in GitHub Desktop.
all pattern extracted to there own partial function
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
object Test extends App { | |
def x(in: Any): List[String] = in match { | |
case i: Int => List(i.toString) | |
case s: String => List(s) | |
case xs: List[_] => xs flatMap x | |
case _ => Nil | |
} | |
val y1: PartialFunction[Any, List[String]] = _ match { | |
case i: Int => List(i.toString) | |
} | |
val y2: PartialFunction[Any, List[String]] = _ match { | |
case s: String => List(s) | |
} | |
val y3: PartialFunction[Any, List[String]] = _ match { | |
case xs: List[_] => xs flatMap y | |
} | |
def y(in: Any): List[String] = { | |
val xs = List(y1, y2, y3) | |
xs find (_ isDefinedAt in) map (_(in)) getOrElse Nil | |
} | |
val xs = List(List(1, 2, "hello"), "abc", 3, List(4)) | |
println(x(xs)) | |
println(y(xs)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment