模式匹配问题,在Scala中实现SplitAt [英] Problems with Pattern matching, implementing SplitAt in scala

查看:217
本文介绍了模式匹配问题,在Scala中实现SplitAt的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用模式匹配来实现scala splitAt,这就是我正在尝试做的事情:

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]())
}

编译器抱怨说:

<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.

谢谢

推荐答案

在模式匹配中应使用`someIndex`和`currentIndex`(常量).

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

Scala编程第15章,第一版. 案例类和模式匹配" 由Martin Odersky,Lex Spoon和Bill Venners撰写:

Chapter 15 of Programming in Scala, First Edition. "Case Classes and Pattern Matching" by Martin Odersky, Lex Spoon, and Bill Venners:

如果需要,您仍然可以为模式使用小写名称 常量,使用两个技巧之一.首先,如果常量是一个字段 对于某些对象,您可以在其前面加上限定符.例如pi 是一个可变模式,但是this.pi或obj.pi是常量,即使 它们以小写字母开头.如果这样不起作用(因为pi 是局部变量,例如),您也可以将变量括起来 姓名记在后面.

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.

这篇关于模式匹配问题,在Scala中实现SplitAt的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆