implementing in operator in scala

7
Implementing IN operator in Scala Boston Area Scala Enthusiasts Nermin Serifovic February 2, 2010

Upload: boston-area-scala-enthusiasts

Post on 16-Jul-2015

1.702 views

Category:

Technology


2 download

TRANSCRIPT

Page 1: Implementing IN operator in Scala

Implementing IN operator in Scala

Boston Area Scala Enthusiasts

Nermin Serifovic

February 2, 2010

Page 2: Implementing IN operator in Scala

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‟)

Page 3: Implementing IN operator in Scala

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

Page 4: Implementing IN operator in Scala

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

Page 5: Implementing IN operator in Scala

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

Page 6: Implementing IN operator in Scala

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"))

}}

Page 7: Implementing IN operator 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?