【问题标题】:Pattern matching doesn't work模式匹配不起作用
【发布时间】:2013-07-20 07:25:12
【问题描述】:

我想知道,为什么这不起作用:

  def example(list: List[Int]) = list match {
    case Nil => println("Nil")
    case List(x) => println(x)
  }                                             

  example(List(11, 3, -5, 5, 889, 955, 1024))

上面写着:

scala.MatchError: List(11, 3, -5, 5, 889, 955, 1024) (of class scala.collection.immutable.$colon$colon)

【问题讨论】:

    标签: scala


    【解决方案1】:

    因为List(x) 只匹配具有一个元素的列表。所以

    def example(list: List[Int]) = list match {
      case Nil => println("Nil")
      case List(x) => println(x)
    }
    

    仅适用于零个或一个元素的列表。

    【讨论】:

      【解决方案2】:

      它不起作用,因为List(x) 表示只有一个元素的列表。检查它:

      def example(list: List[Int]) = list match {
        case Nil => println("Nil")
        case List(x) => println("one element: " + x)
        case xs => println("more elements: " + xs)
      } 
      
      example(List(11, 3, -5, 5, 889, 955, 1024))
      //more elements: List(11, 3, -5, 5, 889, 955, 1024) 
      example(List(5))
      //one element: 5
      

      【讨论】:

      【解决方案3】:

      正如其他发帖者所指出的,List(x) 仅匹配 1 个元素的列表。

      然而,匹配多个元素的语法:

      def example(list: List[Int]) = list match {
        case Nil => println("Nil")
        case List(x @ _*) => println(x)
      }                                             
      
      example(List(11, 3, -5, 5, 889, 955, 1024)) // Prints List(11, 3, -5, 5, 889, 955, 1024)
      

      有趣的是 @ _* 的事情,这使得不同。 _* 匹配重复的参数,x @ 表示“将此绑定到 x”。

      同样适用于任何可以匹配重复元素的模式匹配(例如,Array(x @ _*)Seq(x @ _*))。 List(x @ _*) 也可以匹配空列表,尽管在这种情况下,我们已经匹配了 Nil。

      你也可以使用_*来匹配“其余的”,如:

      def example(list: List[Int]) = list match {
        case Nil => println("Nil")
        case List(x) => println(x)
        case List(x, xs @ _*) => println(x + " and then " + xs)
      }
      

      【讨论】:

      • @Grienders 你能详细说明一下吗?您想了解 (x::xs) 的哪些内容?
      猜你喜欢
      • 2012-07-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多