Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Scala, is there a neat and simple way to compare one value with multiple values

Tags:

equality

scala

Say I have a variable x, and I want to check if it's equal to any one of multiple values a, b, c, d, e (I mean the == equality, not identity).

In an SQL query the same concept is handled with

WHERE x IN (a, b, c, d, e).

Is there something equivalent in Scala that's as straightforward as that? I know it's otherwise possible to do it in one line with a complex expression such as building a HashSet and checking for existence in the set, but I'd prefer to use a simple construct if it's available.

like image 733
Gigatron Avatar asked May 08 '11 13:05

Gigatron


3 Answers

You could implement an in operator as follows:

scala> implicit def anyWithIn[A](a: A) = new {
     |   def in(as: A*) = as.exists(_ == a)
     | }
anyWithIn: [A](a: A)java.lang.Object{def in(as: A*): Boolean}

scala> 5 in (3, 4, 9, 11)
res0: Boolean = false

scala> 5 in (3, 4, 9, 11, 5)
res1: Boolean = true
like image 142
missingfaktor Avatar answered Sep 28 '22 09:09

missingfaktor


I would prefer contains(a) over exists(_ == a):

scala> List(3, 4, 5) contains 4
res0: Boolean = true

scala> List(3, 4, 5) contains 6
res1: Boolean = false

Update: contains is defined in SeqLike, so the above works with any sequence.

Update 2: Here is the definition of contains in SeqLike:

def contains(elem: Any): Boolean = exists (_ == elem)
like image 40
Frank S. Thomas Avatar answered Sep 28 '22 10:09

Frank S. Thomas


Given that a Set[A] is also a A => Boolean, you can just say:

Set(a, b, c, d, e) apply x

It's actually quite nice to define some pimpin' sugar for this:

class PredicateW[A](self : A => Boolean) {
  def ∈:(a : A) = self apply a
}
implicit def pred2wrapper[A](p : A => Boolean) = new PredicateW(p)

Then you can write the code like so:

x ∈: Set(a, b, c, d, e)
like image 37
oxbow_lakes Avatar answered Sep 28 '22 08:09

oxbow_lakes