加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

Scala模式与集合匹配

发布时间:2020-12-16 09:02:06 所属栏目:安全 来源:网络整理
导读:以下不起作用. object Foo { def union(s: Set[Int],t: Set[Int]): Set[Int] = t match { case isEmpty = s case (x:xs) = union(s + x,xs) case _ = throw new Error("bad input") }} error: not found: type xs 如何在一组上进行模式匹配? 解决方法 好吧,
以下不起作用.

object Foo {
    def union(s: Set[Int],t: Set[Int]): Set[Int] = t match {
        case isEmpty => s
        case (x:xs)  => union(s + x,xs)
        case _       => throw new Error("bad input")
    }
}

error: not found: type xs

如何在一组上进行模式匹配?

解决方法

好吧,x:xs表示xs类型的x,所以它不起作用.但是,唉,你不能模式匹配集,因为集合没有定义的顺序.或者,更实际,因为Set上没有提取器.

不过,您可以随时定义自己的:

object SetExtractor {
  def unapplySeq[T](s: Set[T]): Option[Seq[T]] = Some(s.toSeq)
}

例如:

scala> Set(1,2,3) match {
     |   case SetExtractor(x,xs @ _*) => println(s"x: $xnxs: $xs")
     | }
x: 1
xs: ArrayBuffer(2,3)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读