Successfully reported this slideshow.
Your SlideShare is downloading. ×

Implementing IN operator in Scala

Ad
Ad
Ad
Ad
Ad
Ad
Ad
Ad
Ad
Ad
Loading in …3
×

Check these out next

1 of 7 Ad

Implementing IN operator in Scala

Download to read offline

Boston Area Scala Enthusiasts fourth meeting held on Feb 2, 2010.
Talk delivered by Nermin Serifovic.

Boston Area Scala Enthusiasts fourth meeting held on Feb 2, 2010.
Talk delivered by Nermin Serifovic.

Advertisement
Advertisement

More Related Content

Advertisement

Implementing IN operator in Scala

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

Editor's Notes

  • Notes go here
  • As a Java developer, one thing I miss about Pascal is the in operator.Pascal offers set as a fundamental building block in the language.It’s hard to argue that code like this is elegant and easy to write and read.

×