代码之家  ›  专栏  ›  技术社区  ›  klactose

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

  •  7
  • klactose  · 技术社区  · 16 年前

    我已经搜索了一段时间,但找不到任何例子来演示模式匹配case类时@*的用法。

    下面是我所指的应用程序类型的示例。

    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?
    }
    

    }

    如果有人能给我举几个例子,或者给我指一个有几个例子的网页,那就太好了。

    谢谢

    2 回复  |  直到 16 年前
        1
  •  5
  •   Mitch Blevins    16 年前

    记住

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

    绑定 radius 价值观 3.0 结合 t2 匹配的类型2的实例。

    使用您的示例:

    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 绑定到 SomeObject 定义了 MixedTypes . 您可以将其视为mixedtypes的构造函数参数的序列。

        2
  •  3
  •   Community Mohan Dere    9 年前

    Wampler/Payne编写的scala程序 an example .

    还有另外一个问题: Pattern matching a String as Seq[Char]

    每日斯卡拉博客帖子 unapplySeq .