Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looking for examples of how to use "@_*" when doing pattern matching in Scala

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

like image 639
klactose Avatar asked Feb 23 '10 04:02

klactose


People also ask

How do you match a pattern in scala?

A pattern match includes a sequence of alternatives, each starting with the keyword case. Each alternative includes a pattern and one or more expressions, which will be evaluated if the pattern matches. An arrow symbol => separates the pattern from the expressions.

What is the use of scala pattern matching?

Pattern matching is a way of checking the given sequence of tokens for the presence of the specific pattern. It is the most widely used feature in Scala. It is a technique for checking a value against a pattern. It is similar to the switch statement of Java and C.

How is case class used in pattern matching?

Case classes help us use the power of inheritance to perform pattern matching. The case classes extend a common abstract class. The match expression then evaluates a reference of the abstract class against each pattern expressed by each case class.


2 Answers

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.

like image 153
Mitch Blevins Avatar answered Oct 14 '22 05:10

Mitch Blevins


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.

like image 32
huynhjl Avatar answered Oct 14 '22 06:10

huynhjl