寻找如何使用“@_*”的示例在 Scala 中进行模式匹配时

发布于 2024-08-22 18:18:17 字数 451 浏览 9 评论 0原文

我一直在寻找,但找不到任何演示在模式匹配案例类时使用 @_* 的示例。

以下是我所指的此类应用程序的示例。

def findPerimeter(o: SomeObject): Perimeter = o match {
case Type1(length, width) =>
  new Perimeter(0, 0, length, width)
case Type2(radius) =>
  new Perimeter(0, 0, 2*radius, 2*radius)
...

case MixedTypes(group @_*) => {
  \\How could @_* be used to check subpatterns of group?
}

如果

有人可以向我展示一些示例或向我指出一个包含一些示例的网页,那就太好了。

谢谢

I have been searching for a bit but can not locate any examples that demonstrate the usage of @_* while pattern matching case classes.

Below is an example of the kind of application I am referring to.

def findPerimeter(o: SomeObject): Perimeter = o match {
case Type1(length, width) =>
  new Perimeter(0, 0, length, width)
case Type2(radius) =>
  new Perimeter(0, 0, 2*radius, 2*radius)
...

case MixedTypes(group @_*) => {
  \\How could @_* be used to check subpatterns of group?
}

}

If someone could show me some examples or point me to a web page that has a few examples that would be great.

Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

情泪▽动烟 2024-08-29 18:18:17

请记住,诸如

Type2(3.0) match {
  case t2 @ Type2(radius) => //...
}

radius 绑定到值 3.0 并将 t2 绑定到要匹配的 Type2 实例。

使用您的示例:

def findPerimeter(o: SomeObject): Perimeter = o match {
  case Type1(length, width) => new Perimeter(0, 0, length, width)
  case Type2(radius) => new Perimeter(0, 0, 2*radius, 2*radius)
  // ...
  // assume that Perimeter defines a + operator
  case MixedTypes(group @ _*) => group.reduceLeft(findPerimeter(_) + findPerimeter(_))

}

这里,group 绑定到定义 MixedTypesSomeObject 序列。您可以将其视为任意混合类型的构造函数参数的序列。

Remember that something like

Type2(3.0) match {
  case t2 @ Type2(radius) => //...
}

binds radius to the value 3.0 and binds t2 to the instance of Type2 being matched against.

Using your example:

def findPerimeter(o: SomeObject): Perimeter = o match {
  case Type1(length, width) => new Perimeter(0, 0, length, width)
  case Type2(radius) => new Perimeter(0, 0, 2*radius, 2*radius)
  // ...
  // assume that Perimeter defines a + operator
  case MixedTypes(group @ _*) => group.reduceLeft(findPerimeter(_) + findPerimeter(_))

}

Here, group is bound to the sequence of SomeObjects that define the MixedTypes. You can treat is just like a sequence of whatever-the-constructor-args-for-MixedTypes-is.

好倦 2024-08-29 18:18:17

Wampler/Payne 的《Scala 编程》有示例

还有另一个问题:
将字符串匹配为 Seq[Char] 的模式

以及 Daily Scala 博客文章unapplySeq

Programming Scala by Wampler/Payne has an example.

Also some another SO question:
Pattern matching a String as Seq[Char]

And the Daily Scala blog post on unapplySeq.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文