<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Along Came Betty &#187; scala</title>
	<atom:link href="http://blog.darevay.com/category/scala/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.darevay.com</link>
	<description>You know, software and some other stuff like maybe guitar or something</description>
	<lastBuildDate>Tue, 24 Nov 2009 03:21:41 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Remedial Scala: Interpreting Scala from Scala</title>
		<link>http://blog.darevay.com/2009/01/remedial-scala-interpreting-scala-from-scala/</link>
		<comments>http://blog.darevay.com/2009/01/remedial-scala-interpreting-scala-from-scala/#comments</comments>
		<pubDate>Sun, 25 Jan 2009 16:17:56 +0000</pubDate>
		<dc:creator>dave</dc:creator>
				<category><![CDATA[scala]]></category>
		<category><![CDATA[scripting]]></category>

		<guid isPermaLink="false">http://blog.darevay.com/?p=183</guid>
		<description><![CDATA[For my &#8220;learning Scala&#8221; project, rooscaloo, I needed to dynamically generate and compile Scala code as rules are loaded into the engine. I had initially intended to do this as an internal DSL, but I honestly couldn&#8217;t think of a way to handle the fact that variables are bound at match time in the rete [...]]]></description>
			<content:encoded><![CDATA[<p>For my &#8220;learning Scala&#8221; project, <a href="http://rooscaloo.googlecode.com">rooscaloo</a>, I needed to dynamically generate and compile Scala code as rules are loaded into the engine. I had initially intended to do this as an<a href="http://debasishg.blogspot.com/2008/05/designing-internal-dsls-in-scala.html"> internal DSL</a>, but I honestly couldn&#8217;t think of a way to handle the fact that variables are bound at match time in the rete network. This is a learning project anyway, so I decided to just generate code and compile it.  Now, I could have sworn I had seen a Scala scripting example using <a href="http://jcp.org/en/jsr/detail?id=223">JSR-223</a> in a blog somewhere, but couldn&#8217;t find it again.  I only found one very basic example of how to do this, in the <a href="http://lampsvn.epfl.ch/trac/scala/ticket/874">Scala bug tracker</a>. So I figured I&#8217;d write down what I came up with.</p>
<p><em>Note that this code makes use of the <strong>scala.tools.nsc</strong> package which is not part of the standard Scala library. Thus, it may change in future versions of Scala. Also note that after the fact, I was able to track down two partial JSR-223 implementations <a href="http://ifcx.svn.sourceforge.net/viewvc/ifcx/thirdparty/scripting/engines/scala/src/org/ifcx/scripting/scala/ScalaScriptEngine.java?revision=91&amp;view=markup">here</a> and <a href="http://code.google.com/p/netgents/source/browse/trunk/scala-scripting/src/com/netgents/script/scala/ScalaScriptEngine.scala">here</a>. It&#8217;s comforting that I ended up in basically the same place.</em></p>
<p>The example given in the bug tracker works, but it&#8217;s very simple and there are two things it doesn&#8217;t do. First, it prints all its output to stdout, including error information. Second, it doesn&#8217;t show how to retrieve results from executing scripts. That is, code goes in, but nothing comes out. These are both solved pretty easily.  In the first case, we simply supply our own PrintWriter when instantiating the internal Scala interpreter:</p>
<pre>  private val writer = new java.io.StringWriter()
  private val interpreter = new ScalaInterpreter(new Settings(),
                                                 <strong>new PrintWriter(writer)</strong>);

  ...

  def exec(code : String) {
    // Clear the previous output buffer
    writer.getBuffer.setLength(0)

    // Execute the code and catch the result
    val ir = interpreter.interpret(code);

    // Return value or throw an exception based on result
    ir match {
      case Success =&gt; ()
      case Error =&gt; throw new ScriptException("error in: '" +
                                              code + "'\n" + writer toString)
      case Incomplete =&gt; throw new ScriptException("incomplete in :'" +
                                                   code + "'\n" + writer toString)
    }
  }</pre>
<p>For the second issue, returning results, I had to think a little longer, probably longer than necessary. <strong>scala.tools.nsc.Interpreter</strong> doesn&#8217;t return anything besides Success, Error, or Incomplete as seen above. But, you can pass objects in, so I ended up creating a container object to hold the result:</p>
<pre><strong>class ResultHolder(var value : Any)</strong>

  ...

  def eval(code : String) : Any = {
    // Clear the previous output buffer
    writer.getBuffer.setLength(0)

    // Create an object to hold the result and bind in the interpreter
    <strong>val holder = new ResultHolder(null)
    bind("$result__", holder);
</strong>
    // Execute the code and catch the result
    val ir = interpreter.interpret(<strong>"$result__.value = " + code</strong>);

    // Return value or throw an exception based on result
    ir match {
      case Success =&gt; <strong>holder.value</strong>
      case Error =&gt; throw new ScriptException("error in: '" +
                                              code + "'\n" + writer toString)
      case Incomplete =&gt; throw new ScriptException("incomplete in :'" +
                                                   code + "'\n" + writer toString)
    }
  }</pre>
<p>As you can see, I ended up with two separate routines. <strong>exec</strong> executes a Scala statement, ignoring its return value. This is useful for <strong>import</strong>s, class declarations, anything that does not evaluate to a value.  <strong>eval</strong> executes a Scala statement, catches the result and returns it.</p>
<p>Anyway, that&#8217;s about it. It seems that full JSR-223 support is in the plan for Scala. Until then, what I have here works for me and it was a good learning experience. <a href="http://code.google.com/p/rooscaloo/source/browse/trunk/rooscaloo/src/org/darevay/rooscaloo/Interpreter.scala">Here&#8217;s</a> the full source for my solution.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.darevay.com/2009/01/remedial-scala-interpreting-scala-from-scala/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Remedial Scala: XML</title>
		<link>http://blog.darevay.com/2009/01/remedial-scala-xml/</link>
		<comments>http://blog.darevay.com/2009/01/remedial-scala-xml/#comments</comments>
		<pubDate>Thu, 22 Jan 2009 04:20:29 +0000</pubDate>
		<dc:creator>dave</dc:creator>
				<category><![CDATA[scala]]></category>
		<category><![CDATA[xml]]></category>

		<guid isPermaLink="false">http://blog.darevay.com/?p=175</guid>
		<description><![CDATA[Tonight I finally got to the XML chapter of Programming in Scala. I was excited because I had seen a few examples on the web and wanted to try something out that wasn&#8217;t jdom or jax-b or whatever. So, I read the chapter and it was &#8230; short. The authors even admit in the conclusion [...]]]></description>
			<content:encoded><![CDATA[<p>Tonight I finally got to the XML chapter of <a href="http://www.artima.com/shop/programming_in_scala">Programming in Scala</a>. I was excited because I had seen a few examples on the web and wanted to try something out that wasn&#8217;t jdom or jax-b or whatever. So, I read the chapter and it was &#8230; short. The authors even admit in the conclusion that it barely scratches the surface and I have to agree :)</p>
<p>Anyway, my exercise for Scala&#8217;s XML support was adding an XML encoding of rules to <a href="http://rooscaloo.googlecode.com">rooscaloo</a>. My plan is to eventually write a parser with parser combinators, but that&#8217;s not until chapter 31.</p>
<p>Overall, Scala&#8217;s XML support is a dream compared to anything I&#8217;ve done in Java before. I began by creating some case classes for my AST:</p>
<pre>  case class RuleAST(name : String,
                     fireCode : String, unfireCode : String,
                     conditions : ConditionAST*)

  case class ConditionAST

  case class ObjectConditionAST(typeName : String,
                                binding : String,
                                testCode : String) extends ConditionAST

  case class NotAST(children : ConditionAST*) extends ConditionAST</pre>
<p>really simple stuff.  Here&#8217;s what a rule looks like in XML:</p>
<pre>    &lt;rule name="bob-is-not-a-cat-lover"&gt;
      &lt;if&gt;
        &lt;object type="Person" binding="p"&gt; p.name == "bob" &lt;/object&gt;
        &lt;not&gt;
            &lt;object type="Cat" binding="c"&gt; c.owner == p &lt;/object&gt;
        &lt;/not&gt;
      &lt;/if&gt;
      &lt;then&gt;println("bob does not fancy cats")&lt;/then&gt;
      &lt;unfire&gt;Tprintln("bob now owns a cat!")&lt;/unfire&gt;
    &lt;/rule&gt;</pre>
<p><em>(I couldn&#8217;t think of a better name for rule retraction than unfire&#8230;)</em></p>
<p>and here&#8217;s the satisfyingly compact code to convert an XML node to a RuleAST object:</p>
<pre>  def parseRule(node: scala.xml.Node) : RuleAST =
    RuleAST(node \ "@name" text,
            node \ "then" text,
            node \ "unfire" text,
            parseConditionList(node \ "if" \ "_") : _*)

  def parseConditionList(xml : scala.xml.NodeSeq) : Seq[ConditionAST] =
    for(e &lt;- xml)
      yield e match {
        case &lt;object&gt;{ _* }&lt;/object&gt; =&gt; parseObjectCondition(e)
        case &lt;not&gt;{ _* }&lt;/not&gt; =&gt; parseNot(e)
      }

  def parseObjectCondition(xml : scala.xml.Node) : ObjectConditionAST =
    ObjectConditionAST(xml \ "@type" text, xml \ "@binding" text, xml.text)

  def parseNot(xml : scala.xml.Node) : NotAST =
    NotAST(parseConditionList(xml \ "_") : _*)</pre>
<p>This could actually be much more compact but I chose to break it up into methods so I could test each construct individually. Still, I&#8217;m fairly certain there&#8217;s an even better way to do this, but this represents 45 minutes of work including unit tests, so I&#8217;m still pretty happy. One thing I discovered that wasn&#8217;t covered in the book was the use of the <strong>&#8220;_&#8221;</strong> wildcard to get all sub-elements of a node. For example we can see above that I use:</p>
<pre>   node \ "if" \ "_"</pre>
<p>to get the list of all child elements of the <strong>&lt;if&gt;</strong> node.</p>
<p>The <strong>match</strong> statement in <strong>parseConditionList</strong> is a little irritating to me and I feel like there&#8217;s probably a better way to do that.</p>
<p>Just like the book, I&#8217;ve obviously only started to scratch the surface of  Scala&#8217;s XML support. Since I also just read the chapter on <a href="http://www.scala-lang.org/node/112">extractors</a>, it seems like it might be interesting to define extractors to automatically convert XML to an AST. Of course, there&#8217;s also XPath, transforms, etc.</p>
<p>Maybe tomorrow night. It&#8217;s time to sleep.</p>
<p>p.s. here are some more Scala XML resources I&#8217;ve found useful:</p>
<ul>
<li><a href="http://www.scala-lang.org/node/131">A Tour of Scala &#8230;</a></li>
<li><a href="http://www.ibm.com/developerworks/java/library/x-scalaxml/index.html">A nice introduction</a> by Michael Galpin</li>
<li>The Scala XML <a href="http://burak.emir.googlepages.com/scalaxbook.docbk.html">&#8220;book&#8221;</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://blog.darevay.com/2009/01/remedial-scala-xml/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Remedial Scala: Emulating C# Extension Methods</title>
		<link>http://blog.darevay.com/2009/01/remedial-scala-emulating-c-extension-methods/</link>
		<comments>http://blog.darevay.com/2009/01/remedial-scala-emulating-c-extension-methods/#comments</comments>
		<pubDate>Sat, 17 Jan 2009 20:57:40 +0000</pubDate>
		<dc:creator>dave</dc:creator>
				<category><![CDATA[scala]]></category>
		<category><![CDATA[c-sharp]]></category>
		<category><![CDATA[java]]></category>

		<guid isPermaLink="false">http://blog.darevay.com/?p=163</guid>
		<description><![CDATA[I admit that, as a Java programmer, I&#8217;ve been jealous of C#&#8217;s extension methods for a while. Java&#8217;s getting pretty long in the tooth. While C# is adding lots of cool new features, Sun doesn&#8217;t have the balls to even add closures despite three working implementations to choose from.  I get bimonthly reports from a [...]]]></description>
			<content:encoded><![CDATA[<p>I admit that, as a Java programmer, I&#8217;ve been jealous of <a href="http://msdn.microsoft.com/en-us/library/bb383977.aspx">C#&#8217;s extension methods</a> for a while. Java&#8217;s getting pretty long in the tooth. While C# is adding lots of <a href="http://msdn.microsoft.com/en-us/library/bb308959.aspx">cool new features</a>, Sun doesn&#8217;t have the balls to even add closures despite<a href="http://rickyclarkson.blogspot.com/2008/12/java-just-died-no-closures-in-java-7.html"> three working implementations to choose from</a>.  I get bimonthly reports from a former co-worker and C# aficionado of this or that cool feature that Java will never have.  He loves to rub it in.</p>
<p>I know that extension methods are just <a href="http://www.hanselman.com/blog/HowDoExtensionMethodsWorkAndWhyWasANewCLRNotRequired.aspx">syntactic sugar</a> and any Lisp adherent will tell you they&#8217;re really just a poor man&#8217;s version of <a href="http://en.wikipedia.org/wiki/Generic_function">generic functions</a>.  But I want them nonetheless.</p>
<p>So, forget about Java. I&#8217;m pleased to say that in Scala it is easy to emulate extension methods. Here&#8217;s Microsoft&#8217;s example code in C#:</p>
<pre>namespace ExtensionMethods
{
    public static class MyExtensions
    {
        public static int WordCount(this String str)
        {
            return str.Split(new char[] { ' ', '.', '?' },
                             StringSplitOptions.RemoveEmptyEntries).Length;
        }
    }
}</pre>
<p>this just adds a <strong>WordCount</strong> method to the built in string class. Here&#8217;s the equivalent code in Scala, with a <strong>main</strong> method for good measure:</p>
<pre>object Main {

  implicit def stringToWordCounter(s : String) = {
    new {
      def wordCounts : Int = {
        s.split(Array(' ', '.', '?')).map(_ trim).filter(! _.isEmpty).size
      }
    }
  }

  def main(args: Array[String]) {
    println("Hello Extension Methods".wordCounts)
  }

}</pre>
<p>This makes use of Scala&#8217;s support for implicit conversions. If a method is called on an object that doesn&#8217;t exist on that object&#8217;s base type, the compiler searches for an implicit method (<strong>stringToWordCounter</strong> in this case) that converts to a type that does have that method. <strong>stringToWordCounter</strong> converts implicitly to a anonymous class that just happens to have a <strong>wordCount</strong> method. Cool. Note that the returned type can have any number of methods and may also implement traits (interfaces).</p>
<p>One thing I don&#8217;t know about is performance. Implicit conversions mean constructing a new intermediary object to call the method on. Maybe the compiler is smart? Anyway, this is <strong>remedial</strong> Scala, so I&#8217;ll worry about that later.</p>
<p>Also of note in this example is how much nicer the code to split, trim, and filter the input string is. I&#8217;m assuming there&#8217;s some other, more functional way to do this in C# without resorting to the long-winded <strong>StringSplitOptions.RemoveEmptyEntries</strong> flag.</p>
<p>That&#8217;s it for today&#8217;s installment of <strong>Remedial Scala</strong>. See you next time.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.darevay.com/2009/01/remedial-scala-emulating-c-extension-methods/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Remedial Scala : Repeated Parameters and Initializing Collections</title>
		<link>http://blog.darevay.com/2009/01/remedial-scala-repeated-parameters-and-initializing-collections/</link>
		<comments>http://blog.darevay.com/2009/01/remedial-scala-repeated-parameters-and-initializing-collections/#comments</comments>
		<pubDate>Tue, 13 Jan 2009 13:40:39 +0000</pubDate>
		<dc:creator>dave</dc:creator>
				<category><![CDATA[scala]]></category>

		<guid isPermaLink="false">http://blog.darevay.com/?p=150</guid>
		<description><![CDATA[I  only recently began to learn Scala (rooscaloo is coming along nicely, btw). I&#8217;m having a great time and the scala-user mailing list has been a great resource for learning more idiomatic ways to express myself in Scala. Every couple of days I ask a dumb question which ends up teaching me a lot about [...]]]></description>
			<content:encoded><![CDATA[<p>I  only recently began to <a href="http://blog.darevay.com/2009/01/getting-to-know-scala/">learn Scala</a> (<a href="http://rooscaloo.googlecode.com">rooscaloo</a> is coming along nicely, btw). I&#8217;m having a great time and the scala-user mailing list has been a great resource for learning more idiomatic ways to express myself in Scala. Every couple of days I ask a dumb question which ends up teaching me a lot about the language. So I figured I&#8217;d write about what I learn, even if it&#8217;s at a much lower plane of existence than a lot of <a href="http://james-iry.blogspot.com/2007/10/monads-are-elephants-part-3.html">other</a> <a href="http://scala-blogs.org/2008/09/y-combinator-in-scala.html">Scala</a> <a href="http://blog.tmorris.net/continuation-monad-in-scala/">commentary</a> <a href="http://debasishg.blogspot.com/2009/01/subsuming-template-method-pattern.html">that&#8217;s</a> <a href="http://debasishg.blogspot.com/2009/01/higher-order-abstractions-in-scala-with.html">out there</a>.  Hopefully another neophyte may someday find this informative.</p>
<h1>Repeated Parameters</h1>
<p>Today&#8217;s lesson is about two things that I didn&#8217;t initially know were related. First, I wanted to know how to initialize a map with a list of pairs. The Scala <a href="http://www.scala-lang.org/docu/files/api/scala/collection/immutable/Map$object.html">Map</a> constructor take a variable list of pairs (a repeated parameter) to initialize the map. For example:</p>
<pre>   scala&gt; val map = Map((1, 2), (3, 4))
   map: scala.collection.immutable.Map[Int,Int] = Map(1 -&gt; 2, 3 -&gt; 4)</pre>
<p>But, I have a list of pairs, not a parameter list.  So, here&#8217;s what I was doing:</p>
<pre>   val map = Map() ++ listOfPairs</pre>
<p>which worked fine. Basically, it takes an empty map and adds the pairs in the list. It smells a little though and I was sure this wasn&#8217;t idiomatic. So I asked. The correct answer is the <strong>_* </strong>operator of course:</p>
<pre>   scala&gt; val args = List((1, 2), (3, 4))
   args: List[(Int, Int)] = List((1,2), (3,4))

   scala&gt; val map = Map(args : _*)
   map: scala.collection.immutable.Map[Int,Int] = Map(1 -&gt; 2, 3 -&gt; 4)</pre>
<p>When a parameter is followed by <strong>&#8220;: _*&#8221;</strong>, this tells Scala to expand the argument to a variable argument list rather than a single argument.  Funny enough, I actually knew this from chapter 8 of the <a href="http://www.artima.com/shop/programming_in_scala">Programming in Scala</a> book, but sometimes I forget things&#8230;</p>
<p>So, this explains why all of the Scala collection types take just a repeated parameter list for initialization rather than another collection like the Java collections library.</p>
<h1>Turning an Option into a Set</h1>
<p>The revelation above led directly to the solution for my other problem. In particular, I wanted a nice way to convert an <strong>Option </strong>(think of it as a collection with exactly 0 or 1 elements) to a <strong>Set</strong>. I had this code:</p>
<pre>  def toSet[T](o : Option[T]) : Set[T] = {
    o match {
      case Some(some) =&gt; Set(some)
      case None =&gt; Set()
    }
  }</pre>
<p>which works fine, but &#8230;</p>
<p>It turns out that <strong>Option </strong>has a <strong>toList</strong> method so I can pass it to a repeated parameter list to initialize a collection from an <strong>Option</strong>:</p>
<pre>   scala&gt; val s = Set(Some(1).toList : _*)
   s: scala.collection.immutable.Set[Int] = Set(1)</pre>
<p>and:</p>
<pre>   scala&gt; val s = Set(None.toList : _*)
   s: scala.collection.immutable.Set[Nothing] = Set()</pre>
<p>Pretty cool &#8230; Ok, so it isn&#8217;t exactly pretty and I stayed with my utility function just for readability, but it&#8217;s nice when a language has this kind of consistency where the solution to one problem crops up over and over again.</p>
<p>Remedial, eh?</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.darevay.com/2009/01/remedial-scala-repeated-parameters-and-initializing-collections/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Getting to know Scala</title>
		<link>http://blog.darevay.com/2009/01/getting-to-know-scala/</link>
		<comments>http://blog.darevay.com/2009/01/getting-to-know-scala/#comments</comments>
		<pubDate>Sun, 11 Jan 2009 03:19:20 +0000</pubDate>
		<dc:creator>dave</dc:creator>
				<category><![CDATA[scala]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[learning]]></category>
		<category><![CDATA[rete]]></category>

		<guid isPermaLink="false">http://blog.darevay.com/?p=140</guid>
		<description><![CDATA[It&#8217;s conventional wisdom that a programmer should probably learn one new language every year. By my count, in my 10 years as a &#8220;professional&#8221; programmer I&#8217;ve done non-trivial projects in eight languages (chronologically: Matlab, C, C++, Visual Basic, Lisp, Tcl, Python, Java). So, I&#8217;ve got a pretty good average, but a lot of that was [...]]]></description>
			<content:encoded><![CDATA[<p>It&#8217;s conventional wisdom that a programmer should probably <a href="http://blogs.tedneward.com/2008/07/03/Polyglot+Plurality.aspx">learn one new language every year</a>. By my count, in my 10 years as a &#8220;professional&#8221; programmer I&#8217;ve done non-trivial projects in eight languages (chronologically: Matlab, C, C++, Visual Basic, Lisp, Tcl, Python, Java). So, I&#8217;ve got a pretty good average, but a lot of that was concentrated in the first several years. For that last few years, I&#8217;ve been in a mostly Java rut for better or worse.  In an attempt to break the monotony, I started learning <a href="http://www.scala-lang.org/">Scala</a> shortly before the New Year. From the web site:</p>
<blockquote><p>Scala is a general purpose programming language designed to express common programming patterns in a concise, elegant, and type-safe way. It smoothly integrates features of object-oriented and functional languages. It is also fully interoperable with Java.</p></blockquote>
<p>Scala appeals to me on a few fronts. First, it&#8217;s functional aspects are an area I really haven&#8217;t had much experience with other than a brief stint in Lisp many years ago and an occasional lambda in Python. Second, because it runs on the JVM, there&#8217;s a somewhat compelling case that I could actually use it on a project someday without throwing out all of my Java work from the past few years.</p>
<h2>Getting Started</h2>
<p>I started out by reading Ted Neward&#8217;s <a href="http://www.ibm.com/developerworks/views/java/libraryview.jsp?search_by=scala">excellent series of articles</a> on Scala. I read them just to get a feel for the language, but never actually tried running any code. After reading that series, I decided to take the plunge and bought the brand new <a href="http://www.artima.com/shop/programming_in_scala">Programming in Scala</a> book in both digital and analog forms.  It&#8217;s really a pretty good book. It&#8217;s well written and doesn&#8217;t gloss over technical details. The book is technically a tutorial which means it introduces the language in stages. Overall, this is a good approach, but there were a few points that were teasers for later chapters that I wish they would have covered immediately. Two examples:</p>
<ul>
<li>The idea of companion objects for &#8220;new-free&#8221; constructors like List() and Map() is mentioned early on, but they don&#8217;t say how to actually do it until much later. I wanted to know right then!</li>
<li>They briefly discuss val vs. var. vs. def and the <em>UniformAccess Principle</em>, without giving an example. I had to hunt through the rest of the book to find out how to implement it.</li>
</ul>
<p>So now I had the book, time to write some code&#8230;</p>
<h2>The Project</h2>
<p>Oh, first I guess I should say what my &#8220;learning Scala&#8221; project is. I&#8217;m building a very simple, very naive rules engine, <a href="http://rooscaloo.googlecode.com">rooscaloo</a>, in the spirit of <a href="http://jboss.org/drools/">Drools</a> or <a href="http://ruleby.org/">Ruleby</a>. In a nutshell, users write rules that match patterns in memory and do something interesting when a match occurs.  Memory is populated by facts, which in my case are just plain old Scala objects. The matcher is a simple implementation of a <a href="http://en.wikipedia.org/wiki/Rete_algorithm">rete network</a> which has a lot of list manipulation and traversal which I hoped would map nicely onto Scala&#8217;s functional capabilities.</p>
<h2>Choosing an IDE</h2>
<p>First I had to decide on an IDE. The Scala compiler, scalac, is a command-line tool, so of course, vim + ant or something was always an option. But, I&#8217;m old and lazy now, so if I can transfer my <a href="http://blog.jayfields.com/2008/11/things-to-dislike-about-java.html">[ctrl + space]</a> programming habits from Java to Scala, you better believe I will.</p>
<p>Since I&#8217;m generally partial to Eclipse, I first tried out the<a href="http://www.scala-lang.org/node/94"> Scala Eclipse plugin</a>. A somewhat sad trend I&#8217;ve noticed in the Eclipse universe is that the core Java tools, the <a href="http://eclipse.org/jdt">JDT</a>, are generally rock solid and everything else (including the several Eclipse plugins I&#8217;ve built myself) just doesn&#8217;t work that well.  The complexity of the Eclipse API, especially the threading model, can&#8217;t help much.</p>
<p>Anyway, I installed the plugin, created a test project and things seemed to work pretty well.  I started coding and went to add my first unit test. Since I know JUnit, and like Eclipse&#8217;s green bar, I went with that. I added the JUnit library to the project in the usual way and &#8230; my unit test code wouldn&#8217;t compile, couldn&#8217;t find JUnit. I fiddled around with manually adding the JUnit jar, restarting Eclipse and some other stuff and eventually got it to work, but wasn&#8217;t that confident. As a test, I tried creating a fresh Scala project and immediately adding JUnit support and that worked flawlessly.  These are the little details of Eclipse plugin development that really kill you.</p>
<p>Finally, I continued coding, and at some point decided to rename a file. This was a mistake. It basically killed Eclipse, flooding it with errors and leaving the project in a really weird state when I restarted. That ended it for me. I really need to be able to rename files.</p>
<p>My next stop was the <a href="http://wiki.netbeans.org/Scala">NetBeans Scala plugin</a>. For most Java development, I&#8217;ve generally found NetBeans pretty inferior to Eclipse. The editor is more clunky, and having to manually build my code just seems prehistoric.  Anyway, I gave the Scala plugin a try and so far, I&#8217;ve been pretty happy with it. <a href="http://blogtrader.net/page/dcaoyuan/entry/scala_for_netbeans_screenshot_121">JUnit support </a>&#8220;just worked&#8221;. Code completion works about as much as I&#8217;d expect it to (maybe 50%, so worse than Java, but better than a lot of dynamic languages), the editor is bearable, and the debugger seems to work fine.</p>
<p>The only issue I&#8217;ve had is that one of my source files seems to give the editor (or compiler, or whatever is behind the editor) fits. I&#8217;ll type a character (any character) and the whole UI will freeze for a few seconds.  I&#8217;ve seen similar issues reported on the scala-tools mailing list, so maybe it&#8217;s a more general problem.</p>
<p>I&#8217;ll stick with NetBeans I guess until something better comes along.</p>
<h2>Language Highlights</h2>
<p>I&#8217;ve only scratched the surface of Scala (and actually only gotten through the first 16 chapters of the Scala book), so here I&#8217;ll just present my favorite parts of the language that I&#8217;ve actually used.</p>
<p><em>Now that I&#8217;ve written it, this is a pretty haphazard list. I&#8217;m going to leave it though mostly because I&#8217;m too tired to rethink what I want to say&#8230;</em></p>
<h3>Option[T]</h3>
<p><strong>Option[T]</strong> is a Scala datatype that encapsulates the sentinel value role usually filled by <strong>null</strong> in Java. For example, in Java, <strong>Map.get()</strong> returns <strong>null</strong> if the value isn&#8217;t present. This is an incredibly common pattern.  Because of it, I spend my programming time trying to decide whether a method can return <strong>null</strong> or whether it is safe to pass <strong>null</strong> as an argument to a method, etc. Sometimes it&#8217;s documented, others I have to guess or just test and see what happens. <strong>Option[T]</strong> has two possible values: <strong>Some</strong> and <strong>None</strong>. <strong>Some</strong> holds a non-null instance of a type <strong>T</strong>. By consistently using <strong>Option[T]</strong> in APIs, client code is forced to check for <strong>null</strong> return values and knows when a parameter accepts a <strong>null</strong> value. Testing for <strong>null</strong> (<strong>None</strong>, actually) is done with Scala&#8217;s really cool pattern matching construct:</p>
<pre>    val name = getUserName()
    name match {
        case Some(n) =&gt; println("User name is " + n)
        case None =&gt;    // Do nothing
    }</pre>
<p>This can get a little tedious, but Scala has a nice solution. First, I&#8217;ve found it useful to think of a <strong>Option[T]</strong> as a collection of T that can hold exactly 0 or 1 values. Each collection in Scala has a <strong>foreach</strong> that takes a function to execute on the members of the collection. So, <strong>Option[T]</strong> has a <strong>foreach</strong> method as well. The pattern match above translates to the following <strong>foreach</strong> call:</p>
<pre>    getUserName().foreach(println("User name is " + _))</pre>
<h3>foreach, map, and friends</h3>
<p>Scala collections support functional iteration, that is you pass a function to the collection and it is called for each member in the collection. This is <strong>such</strong> an improvement over Java, even Java&#8217;s kinda new for-each construct. Here&#8217;s an example of rete left activation from my project:</p>
<pre>    val nt = newToken(Some(token), item)
    children.foreach(_.leftActivate(nt))</pre>
<p>In Java this would look something like:</p>
<pre>    final Token nt = newToken(token, item);
    for(BetaMemoryChild child : children)
    {
        child.leftActivate(nt);
    }</pre>
<p>which isn&#8217;t that bad, but it really adds up, especially when the body of the loop is more complicated, or if the member type is something like <strong>Map.Entry&lt;String, Person&gt;</strong>.</p>
<h3>Type Inferencing</h3>
<p>As indicated in the examples above, Scala uses type inferencing which means it figures out the types of variables based on what&#8217;s assigned to them.  This really cuts down on all the Java boilerplate while maintaining static typing. There&#8217;s a pretty good explanation <a href="http://www.codecommit.com/blog/scala/what-is-hindley-milner-and-why-is-it-cool">here</a>.</p>
<h3>mkString()</h3>
<p>This is a really stupid little thing, but every Scala collection has a <strong>mkString()</strong> method that takes a string delimiter and joins the values in the collection:</p>
<pre>  scala&gt; val r = List(1, 2, 3, 4, 5)
  r: List[Int] = List(1, 2, 3, 4, 5)

  scala&gt; r.mkString(", ")
  res0: String = 1, 2, 3, 4, 5</pre>
<p>If I had a nickel for every time I&#8217;ve written <strong>StringUtils.join()</strong> in a Java project &#8230;</p>
<h2>Conclusion</h2>
<p>Overall, after 10 days of use, I&#8217;m loving Scala. I think I&#8217;ve barely scratched the surface of what it can do. My little rules engine, <a href="http://rooscaloo.googlecode.com">rooscaloo</a>, has been a pretty good driver for learning the language so far. It has enough algorithmic and data structure variety that I&#8217;ve been able to find ways to apply Scala constructs in many areas. It&#8217;s probably not going to be very efficient or powerful, but it will have served its purpose.</p>
<p>I&#8217;m looking forward to trying out <a href="http://www.ibm.com/developerworks/java/library/j-scala10248.html">parser combinators</a> to define the rule language. Right now, I&#8217;m just building rules programmatically, which is still far easier and more readable than the equivalent Java code.  I initially thought I might be able to encode the rules as an embedded DSL in Scala with it&#8217;s <a href="http://www.scala-lang.org/node/131">incredibly flexible syntax</a>, but I&#8217;m not sure I&#8217;ll be able to get the affect I want and I need an excuse to try out the parser stuff :)</p>
<h2>Links</h2>
<p>Below are some links to information on Scala that I&#8217;ve found particularly helpful:</p>
<ul>
<li><a href="http://jim-mcbeath.blogspot.com/2008/09/scala-syntax-primer.html">Scala Syntax Primer</a> &#8211; This is really a great cheatsheet for the language. Jim McBreath also has several other equally useful Scala pages on his blog.</li>
<li><a href="http://www.scala-lang.org/docu/files/api/index.html">Scala API</a></li>
<li><a href="http://www.ibm.com/developerworks/views/java/libraryview.jsp?search_by=scala">The busy Java developer&#8217;s guide to Scala</a> &#8211; Ted Neward&#8217;s excellent introductory series</li>
<li><a href="http://www.drmaciver.com/planetscala/">Planet Scala</a> &#8211; A Scala news aggregator</li>
</ul>
<p>I&#8217;ve also spent a little time on the Scala mailing lists and have found the community responsive and friendly.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.darevay.com/2009/01/getting-to-know-scala/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>
