Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pattern-match against every numeric class in one case?

Suppose I have

def foo(x: Any) = x match {
  case s: String => println(0)
  case i: Int => println(1)
  case l: Long => println(2)
  //...
}

Is there any way to make something like the following?

def foo(x: Any) = x match {
  case s: String => println(0)
  case i: Numeric => println("Numeric")
}
like image 719
tkroman Avatar asked Nov 03 '13 19:11

tkroman


People also ask

What is one way to implement pattern matching on methods?

The match keyword provides a convenient way of applying a function (like the pattern matching function above) to an object. Try the following example program, which matches a value against patterns of different types.

Which method of case class allows using objects in pattern matching?

Case classes are Scala's way to allow pattern matching on objects without requiring a large amount of boilerplate. In the common case, all you need to do is add a single case keyword to each class that you want to be pattern matchable.

What is pattern matching rules?

Matches any number (or none) of the single character that immediately precedes it. For example, bugs* will match bugs (one s ) or bug (no s 's). The character preceding the * can be one that is specified by a regular expression. For example, since . (dot) means any character, .

How do you match a pattern in C#?

C# pattern matching is a feature that allows us to perform matching on data or any object. We can perform pattern matching using the is expression and switch statement. is expression is used to check, whether an object is compatible with given type or not. In the following example, we are implementing is expression.


1 Answers

You could try this:

def foo[A](x: A)(implicit num: Numeric[A] = null) = Option(num) match {
  case Some(num) => println("Numeric: " + x.getClass.getName)
  case None => println(0)
}

Then this

foo(1)
foo(2.0)
foo(BigDecimal(3))
foo('c')
foo("no")

will print

Numeric: java.lang.Integer
Numeric: java.lang.Double
Numeric: scala.math.BigDecimal
Numeric: java.lang.Character
0

Note that obtaining a null implicit parameter would not mean that no such implicit exist, but just that none was found at compile time in the search scope for implicits.

like image 143
Jean-Philippe Pellet Avatar answered Oct 22 '22 03:10

Jean-Philippe Pellet