Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
861 views
in Technique[技术] by (71.8m points)

list - Problems with Pattern matching, implementing SplitAt in scala

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...