【问题标题】:Problems with Pattern matching, implementing SplitAt in scala模式匹配的问题,在scala中实现SplitAt
【发布时间】:2012-06-07 10:47:30
【问题描述】:

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

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)

谁能指出我在这里做错了什么以及为什么我会收到无法访问的代码错误。

谢谢

【问题讨论】:

    标签: list scala split pattern-matching


    【解决方案1】:

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

    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:

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

    【讨论】:

    • -感谢您的回复,但我不太明白。从编译器的角度来看,someIndex 和 currentIndex 不是常量吗?
    • @sc_ray 对于 scala 编译器,SomeIndex`someIndex` 是模式匹配中的常量,但 someIndex 是可变模式。请参阅“变量还是常量?”在Chapter 15 of Programming in Scala
    • 这太古怪了。我学到了一些新东西。感谢您指出。我的 sn-p 还有其他问题,但无法访问的代码问题已经解决。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-06
    • 1970-01-01
    • 1970-01-01
    • 2012-10-31
    • 2011-02-03
    • 2016-05-17
    相关资源
    最近更新 更多