implementing in operator in scala
TRANSCRIPT
Implementing IN operator in Scala
Boston Area Scala Enthusiasts
Nermin Serifovic
February 2, 2010
Pascal provides the in operator:
if 5 in [1, 2, 3, 4, 5, 6] then write (“5 is in the set”);
SQL allows it too:
Select *From EmployeesWhere LastName IN („Smith‟, „Garcia‟, „Johnson‟, „Lee‟)
Ideally, would like to write something like this in Scala:
if (5 in [1, 2, 3]) foundIt = true
Or:
if (5 in (1, 2, 3)) foundIt = true
Valid in Groovy: def list = [5, 6, 7, 8] However, Scala has no literals for Lists, Sets, etc…
All brackets and parenthesis are already reserved:[]: type parameterization(): tuples{}: code block<>: relational methods
Acceptable syntax:
if (5 in List(1, 2, 3)) foundIt = true
or:
if (“Scala” in Array(“Programming”, “in”, “Scala”) foundIt = true
Extra credit:
if (5 not in List(1, 2, 3)) foundIt = false
instead of:
if !(5 in List(1, 2, 3)) foundIt = false
Operands.scala:
package in.nerm.scala.ltalk1
class InOperand[A](a: A) {def in(seq: Seq[A]): Boolean = seq.contains(a)
}
object OperandConversions {implicit def toInOperand[A](a: A): InOperand[A] = new InOperand(a)
}
Note: parameterized, so it’s not possible to say:
if (5 in List(“white”, “blue”) foundIt = true
InOperandTests.scala:
package in.nerm.scala.ltalk1
import in.nerm.scala.ltalk1.OperandConversions._
import org.testng.annotations.Testimport org.scalatest.testng.TestNGSuite
class InOperandTests extends TestNGSuite {@Test def verifyIn() {
assert(5 in List(1, 2, 3, 4, 5, 6))assert(!(7 in Array(1, 2, 3, 4, 5, 6)))assert("Scala" in List("Programming", "in", "Scala"))
}}
Given that:
5 not in List(1, 2, 3)
gets interpreted as:
5.not(in).List(1, 2, 3)
is it really possible to implement it?
If not, how close can we get?