gpt4 book ai didi

scala - 匹配Scala中列表的第n个元素

转载 作者:行者123 更新时间:2023-12-04 04:57:53 28 4
gpt4 key购买 nike

将值匹配到列表的第n个元素的最佳Scala惯用法是什么?

天真的方法显然行不通:

scala> val list = List(5,6,7)
list: List[Int] = List(5, 6, 7)

scala> val x = 7
x: Int = 7

scala> x match { case list(2) => true; case _ => false }
<console>:10: error: value list is not a case class constructor, nor does it have an unapply/unapplySeq method
x match { case list(2) => true; case _ => false }

要澄清-这个问题不是关于如何将值与列表的第n个元素进行比较-而是关于是否可以使用匹配来完成。

最佳答案

看,实例提取器的强大功能! (stdlib中的Regex类的工作方式与此类似)

case class Nth[A](which: Int) {
def unapply(in: List[A]): Option[A] = if (in.size >= which+1) Some(in(which)) else None
}

val second = Nth[Int](1)

List(2,4,6) match {
case second(4) => println("yep!")
case x => println("nope!")
}

关于scala - 匹配Scala中列表的第n个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6840071/

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