gpt4 book ai didi

scala - Scala中列表的模式匹配结束/中间

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

有人可以给我一个更简单的以下代码的解决方案(它正在展开给定结构 0xFC :: len :: payload :: ... :: 0x0A :: 0x0D 的整数列表):

object Payload {
def unapply(z: List[Int]): Option[List[Int]] = if (z.length == z.head + 1) Some(z tail) else None
}

object EndToken {
def unapply(z: List[Int]): Option[List[Int]] = z.reverse match {
case 0x0D :: 0x0A :: tail => Some(tail.reverse)
case _ => None
}
}

object Message {
def unapply(z: List[Int]): Option[List[Int]] = z match {
case 0xFC :: EndToken(x) => Some(x)
case _ => None
}
}

object Main extends App {
val x = List(0xFC, 0x03, 0x01, 0x02, 0x03, 0x0A, 0x0D)

x match {
case Message(Payload(payload)) => println (payload)
case _ => println("No match")
}
}

就像是:
object Message {
def unapply(z: List[Int]): Option[List[Int]] = z match {
case 0xFC :: Payload(x) :: 0x0A :: 0x0D => Some(x)
case _ => None
}
}

但是,当然, ::期待元素,而不是列表,所以它不起作用......

最佳答案

这是我的解决方案(尽管在重新阅读时我认为它就像 Daniel 的解决方案)。它基于中缀操作模式,其中模式 op(p, q)是一样的p op q .

运算符以 : 开头与 :: 具有相同的优先级并以 : 结尾关联到右边。 (len, payload) :!: tail:!:((len, payload), tail) 相同.基于长度的有效载荷提取的实现有点复杂,但主要是因为我只想遍历列表一次。

object :!: {
type LengthPayload = (Int, List[Int]) // (len, payload)
// returns ((len, payload), unparsed)
def unapply(z: List[Int]): Option[(LengthPayload, List[Int])] = {
if (z == Nil) None
else {
val len = z.head
// use ListBuffer to traverse the list only once
val buf = collection.mutable.ListBuffer[Int]()
def take(l: Int, list: List[Int]): Option[(LengthPayload, List[Int])] = {
list match {
case Nil if l > 0 => None
case _ if l == 0 => Some((len, buf.toList), list)
case _ => buf += list.head; take(l - 1, list.tail)
}
}
take(len, z.tail)
}
}
}

然后消息变得更简单(视觉上):
object Message {
def unapply(z: List[Int]): Option[List[Int]] = z match {
case 0xFC :: (len, payload) :!: 0x0A :: 0x0D :: Nil => Some(payload)
case _ => None
}
}

结果:
val x = List(0xFC, 0x03, 0x01, 0x02, 0x03, 0x0A, 0x0D)
x match {
case Message(payload) => println(payload)
case _ => println("No match")
}
// List(1, 2, 3)

关于scala - Scala中列表的模式匹配结束/中间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7915559/

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