vararg 的 Scala 模式匹配

2024-01-11

我只是想在 scala 上做一些实践,并尝试自己实现 List.concat 函数。这是代码

  def concat[A](lists : Traversable[A]*):List[A]={
    println("concat called")
    lists match {
      case Nil => Nil
      case x :: Nil => (x :\ List.empty[A])((elem,list)=> elem::list)
      case x:: xs => (x :\ concat(xs:_*))((elem,list)=> elem :: list)
    }
  }

但是当我尝试调用这个方法时

concat(List(1,2,3),List(2,3,4),List(4,5,6),List(6,7,8))

我收到错误

Exception in thread "main" scala.MatchError: WrappedArray(List(1, 2, 3), List(2, 3, 4), List(4, 5, 6), List(6, 7, 8)) (of class scala.collection.mutable.WrappedArray$ofRef)

有人可以解释我在这里做错了什么吗? 提前致谢


瓦拉格斯是一个Seq你可以像在Seq,不像清单上的那样。这是一个例子:

@ a(1, 2, 3) 
res1: Seq[Int] = Array(1, 2, 3)
@ def a(x: Int*) = x match {
                  case Seq() => "empty"
                  case Seq(a) => s"single $a"
                  case Seq(a, as @ _*) => s"multiple: $a, $as"
                } 
defined function a
@ a(1, 2, 3, 4) 
res3: String = "multiple: 1, WrappedArray(2, 3, 4)"
@ a(1, 2) 
res4: String = "multiple: 1, WrappedArray(2)"
@ a(1) 
res5: String = "single 1"

进行这样的匹配Nil and x :: xs通常意味着,您可以简单地使用foldLeft,它就是这样做的。

def concat[A](lists: Traversable[A]*): List[A] =
    lists.foldLeft(List.empty[A])(_ ++ _)

请注意,匹配Nil and x :: xs, where xs can be Nil, 足够。你的第二个case可以简单地删除。

看看那些:

case Nil => Nil
case x :: Nil => (x :\ List.empty[A])(_ :: _)
case x :: xs  => (x :\ concat(xs:_*))(_ :: _)

最后两个是一样的。如果是第三种情况xs == Nil然后代替concat(xs:_*)你会得到你的Nil,这与List.empty[A](如果类型推断正确)。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

vararg 的 Scala 模式匹配 的相关文章

随机推荐