gpt4 book ai didi

scala - 模式匹配序列理解的惯用方式是什么?

转载 作者:行者123 更新时间:2023-12-03 12:34:15 25 4
gpt4 key购买 nike

val x = for(i <- 1 to 3) yield i
x match {
case 1 :: rest => ... // compile error
}



构造函数不能实例化为期望的类型;发现:
collection.immutable.::[B]必需:
scala.collection.immutable.IndexedSeq [Int]


这是与 MatchError when match receives an IndexedSeq but not a LinearSeq相同的问题。

问题是,如何正确做?在所有地方添加 .toList似乎都不正确。创建一个处理每个 Seq的自己的提取器(如另一个问题的答案中所述),如果每个人都这样做会导致混乱。

我想的问题是,为什么我不能影响序列理解的返回类型,或者:为什么标准库中的这种广义 Seq提取器部分不起作用?

最佳答案

好了,您可以对任何序列进行模式匹配:

case Seq(a, b, rest @ _ *) =>


例如:

scala> def mtch(s: Seq[Int]) = s match { 
| case Seq(a, b, rest @ _ *) => println("Found " + a + " and " + b)
| case _ => println("Bah")
| }
mtch: (s: Seq[Int])Unit


然后,它将匹配具有(大于或等于)2个元素的任何序列

scala> mtch(List(1, 2, 3, 4))
Found 1 and 2

scala> mtch(Seq(1, 2, 3))
Found 1 and 2

scala> mtch(Vector(1, 2))
Found 1 and 2

scala> mtch(Vector(1))
Bah

关于scala - 模式匹配序列理解的惯用方式是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11503033/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com