问题
I am trying to implement the scala splitAt using pattern matching and this is what I am trying to do:
def split[T](someIndex:Int,someList:List[T]):(List[T],List[T]) = {
def splitHelper[T](currentIndex:Int,someList:List[T],headList:List[T]):(List[T],List[T])= {
(currentIndex,someList) match {
case (someIndex,x::tail) => (x::headList,tail)
case (currentIndex,x::y) => splitHelper(currentIndex+1,y,x::headList)
case _ => (headList,headList)
}
}
splitHelper(0,someList,List[T]())
}
The compiler is complaining by saying:
<console>:15: error: unreachable code
case (currentIndex,x::y) => splitHelper(currentIndex+1,y,x::headList)
Can someone point out what I am doing wrong here and why I am getting the unreachable code error.
Thanks
回答1:
You should use `someIndex` and `currentIndex` (constants) in pattern matching.
scala> val a = 1
a: Int = 1
scala> 2 match {
| case a => println(a)
| }
2
scala> 2 match {
| case `a` => println("a")
| case _ => println("Oops")
| }
Oops
Chapter 15 of Programming in Scala, First Edition. "Case Classes and Pattern Matching" by Martin Odersky, Lex Spoon, and Bill Venners:
If you need to, you can still use a lowercase name for a pattern constant, using one of two tricks. First, if the constant is a field of some object, you can prefix it with a qualifier. For instance, pi is a variable pattern, but this.pi or obj.pi are constants even though they start with lowercase letters. If that does not work (because pi is a local variable, say), you can alternatively enclose the variable name in back ticks.
来源:https://stackoverflow.com/questions/10863067/problems-with-pattern-matching-implementing-splitat-in-scala