<?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>Gary Boone, PhD &#187; Scala</title>
	<atom:link href="http://garyboone.com/category/scala/feed/" rel="self" type="application/rss+xml" />
	<link>http://garyboone.com</link>
	<description>Clippings, code snippets, and other searchable web notes</description>
	<lastBuildDate>Mon, 21 Jun 2010 20:42:28 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=abc</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Fix: Jetty and ScalaObject Not Found</title>
		<link>http://garyboone.com/2010/06/fix-jetty-and-scalaobject-not-found/</link>
		<comments>http://garyboone.com/2010/06/fix-jetty-and-scalaobject-not-found/#comments</comments>
		<pubDate>Mon, 21 Jun 2010 20:42:28 +0000</pubDate>
		<dc:creator>gary</dc:creator>
				<category><![CDATA[Coding]]></category>
		<category><![CDATA[Scala]]></category>

		<guid isPermaLink="false">http://garyboone.com/?p=260</guid>
		<description><![CDATA[Working with Vaadin, Jetty, Scala and Eclipse, I&#8217;ve seen intermittent deployment failures in which the web application would fail with a 500 error and

Problem accessing /HomepageDashboard/. Reason:
    scala/ScalaObject
Caused by:
java.lang.NoClassDefFoundError: scala/ScalaObject

The problem is that the scala library files are not being copied correctly into the WEB-INFO/lib directory. This omission can be verified by [...]]]></description>
			<content:encoded><![CDATA[<p>Working with Vaadin, Jetty, Scala and Eclipse, I&#8217;ve seen intermittent deployment failures in which the web application would fail with a 500 error and</p>
<blockquote><p>
Problem accessing /HomepageDashboard/. Reason:</p>
<p>    scala/ScalaObject<br />
Caused by:</p>
<p>java.lang.NoClassDefFoundError: scala/ScalaObject
</p></blockquote>
<p>The problem is that the scala library files are not being copied correctly into the WEB-INFO/lib directory. This omission can be verified by looking into the war file:</p>
<blockquote><p>
jar tvf HomepageDashboard.war
</p></blockquote>
<p>for the content the WEB-INFO/lib directory.</p>
<p>Some suggested fixes, such as checking the scala library in the project&#8217;s &#8220;Java EE Modules Dependencies&#8221; have not worked consistently for me. Instead, the simple solution is to just manually copy the files where they need to go. The files are found inside the Scala distribution jar. Just extract and copy the needed files:</p>
<blockquote><p>
jar xvf scala.library_2.7.7.final.jar<br />
cp lib/scala-dbc.jar lib/scala-library.jar lib/scala-swing.jar WebContent/WEB-INF/lib/
</p></blockquote>
<p>When the eclipse plugin deploys correctly, it copies all three. You probably only need the scala-library.jar.</p>
]]></content:encoded>
			<wfw:commentRss>http://garyboone.com/2010/06/fix-jetty-and-scalaobject-not-found/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Scala Linear Regression vs Excel</title>
		<link>http://garyboone.com/2010/04/scala-linear-regression-vs-excel/</link>
		<comments>http://garyboone.com/2010/04/scala-linear-regression-vs-excel/#comments</comments>
		<pubDate>Wed, 07 Apr 2010 17:04:06 +0000</pubDate>
		<dc:creator>gary</dc:creator>
				<category><![CDATA[Scala]]></category>
		<category><![CDATA[regression]]></category>

		<guid isPermaLink="false">http://garyboone.com/?p=252</guid>
		<description><![CDATA[In the previous post, I showed how to call multivariate linear regression functions in the Apache Commons Math Statistics library. You might want to compare your results to Excel, perhaps to check your implementation or because you manually develop your analytic process before automating it in code. Here are some tips for comparing Excel results [...]]]></description>
			<content:encoded><![CDATA[<p>In the <a href="http://garyboone.com/2010/04/easy-multivariate-linear-regression-in-scala/">previous post</a>, I showed how to call multivariate linear regression functions in the <a href="http://commons.apache.org/math/userguide/stat.html#a1.5_Multiple_linear_regression">Apache Commons Math Statistics</a> library. You might want to compare your results to Excel, perhaps to check your implementation or because you manually develop your analytic process before automating it in code. Here are some tips for comparing Excel results with those from code.</p>
<p>First, to perform a multivariate linear regression in Excel, use the LINEST function. It requires a formula array to see all of the results, so <em>control-U</em> and <em>command-enter</em> are your friends. Select an 5 row by <em>n</em> column group of cells, where <em>n</em> is the number of variables you&#8217;re fitting. Hit control-U to edit. Enter &#8220;=linest(y,x,1,1)&#8221; where <em>y</em> covers your output values and <em>x</em> covers the <em>n</em> columns of input values. Then hit <em>command-enter</em> to set the array formula for all of the cells. Check the Excel help for more information about LINEST usage.</p>
<p>Once you&#8217;ve figured out the array formula gymnastics, note that the coefficients are returned backwards! That&#8217;s right, the first row of the array formula contains the calculated coefficients for your fit, but in reverse order compared to the order of your input <em>x</em> columns. Go figure. You can even see this dyslexia in the third example in the LINEST help. Look for the section where the regression equation is constructed using the new coefficients.</p>
<p>The third parameter may cause confusion. If you&#8217;ve used LINEST for simple regressions, you may have used <em>linest(y,x,,1)</em> as your function, where x and y are columns. In that case, LINEST provides the slope in row 1, column 1 of the output array, and the intercept in row 1, column 2. Above we set the third parameter to 1 or true, which causes Excel to force the regression plane through the origin. Doing so allows us to compare results between Excel and the Commons Math regression functions. But wait, what if I don&#8217;t want the fit to go through the origin? What if I have no reason to think my function goes through 0? </p>
<p>It&#8217;s actually the standard way of doing regression. Derivations of regression equations don&#8217;t treat the intercept calculation separately. Instead, it&#8217;s built in. Remember, linear regression is linear on the <em>regression coefficients</em>. The function on the <em>coefficients</em> goes through the origin. The function you construct with those coefficients may or may not&#8230;<br />
If you want a constant value in your regressor variables, add it as a column. The resulting coefficient is the intercept. More specifically, regression provides an output coefficient for each column of input. To create a non-zero intercept, add a column of 1s to your data. Regression will find a coefficient for that column. It will be the constant part of your function, the intercept. </p>
<p>For example, when fitting a single column of data, Excel allows you to input an <em>x</em> column and a <em>y</em> column. That&#8217;s one input variable, <em>x</em>. Then <em>linest(y,x,,1)</em> will return <em>two</em> values, the slope and the intercept. A more generalized way about thinking about this problem is to use two input columns: the original <em>x</em> values and a columns of 1s. Then <em>linest(y,x,1,1)</em> returns a coefficient for each column. The resulting equation is <em>y</em>=<em>b1</em> * <em>x1</em> + <em>b0</em> * <em>x0</em>, where <em>x0</em> is always 1. </p>
<p>With the generalized view, we can now compare results between Excel and coded results such as from Commons Math. The Excel coefficients in the first row of the LINEST array function and the values returned by <em>estimateRegressionParameters()</em> should match. </p>
<p>For example, to fit a parabola in both systems, we would perform a linear regression on <em>a*x^2 + b*x + c</em>. Create columns containing <em>x^2</em>, <em>x</em>, and <em>1</em>. Then the regression will return <em>a</em>, <em>b</em>, and <em>c</em>.</p>
<p>Finally, note that that Excel returns the residual and regressor sum of squares. You can use these to check the the r-squared calculations in your code: <em>r^2</em> = 1-<em>ssRes</em>/(<em>ssRes</em>+<em>ssReg</em>).</p>
]]></content:encoded>
			<wfw:commentRss>http://garyboone.com/2010/04/scala-linear-regression-vs-excel/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Easy Multivariate Linear Regression in Scala</title>
		<link>http://garyboone.com/2010/04/easy-multivariate-linear-regression-in-scala/</link>
		<comments>http://garyboone.com/2010/04/easy-multivariate-linear-regression-in-scala/#comments</comments>
		<pubDate>Wed, 07 Apr 2010 15:33:57 +0000</pubDate>
		<dc:creator>gary</dc:creator>
				<category><![CDATA[Scala]]></category>

		<guid isPermaLink="false">http://garyboone.com/?p=250</guid>
		<description><![CDATA[Linear Regression in Scala is as easy as calling the routines in the Apache Commons Math jar. We just need to add the calculation of the correlation coefficient, aka r^2, to see how well we fit. Here&#8217;s how:
Download the library from here and put the commons-math-2.1.jar file on your classpath. Here&#8217;s the example in the [...]]]></description>
			<content:encoded><![CDATA[<p>Linear Regression in Scala is as easy as calling the routines in the Apache Commons Math jar. We just need to add the calculation of the correlation coefficient, aka r^2, to see how well we fit. Here&#8217;s how:</p>
<p>Download the library from <a href="http://commons.apache.org/math/download_math.cgi">here</a> and put the commons-math-2.1.jar file on your classpath. Here&#8217;s the example in the documentation converted to Scala:</p>
<pre class="brush: scala;">
		val regression = new OLSMultipleLinearRegression()
		// example from apache: http://commons.apache.org/math/userguide/stat.html#a1.5_Multiple_linear_regression
		val y = Array(11.0, 12.0, 13.0, 14.0, 15.0, 16.0)
		val x = new Array[Array[Double]](6,6)
		x(0) = Array(1.0, 0, 0, 0, 0, 0)
		x(1) = Array(1.0, 2.0, 0, 0, 0, 0)
		x(2) = Array(1.0, 0, 3.0, 0, 0, 0)
		x(3) = Array(1.0, 0, 0, 4.0, 0, 0)
		x(4) = Array(1.0, 0, 0, 0, 5.0, 0)
		x(5) = Array(1.0, 0, 0, 0, 0, 6.0)

		this.regression.newSampleData(y, x) 

		val beta = this.regression.estimateRegressionParameters()
		println(&quot;betas: &quot; + beta.map(&quot;%.3f&quot;.format(_)).mkString(&quot;, &quot;))

		// residuals, if needed
		val residuals = this.regression.estimateResiduals()
</pre>
<p>This works so cleanly because Scala compiles Array[Double] to double[]. It&#8217;s compatible with the Java library, while still allowing all the cool Scala functions like map(). </p>
<p>Commons Math provides the matrix inversion needed to solve the normal equation and return the desired equation coefficients. But it doesn&#8217;t provide the correlation coefficient, often called &#8220;r-squared,&#8221; which tells you how much of the data&#8217;s variance is explained by the regression. We can add that calculation with the following code. Given the original Y values and the residuals, use:</p>
<pre class="brush: scala;">
	def calcRSquared(y:Array[Double], residuals:Array[Double]) = {
		val ssReg = sumSq(y.zip(residuals).map{case(a,b) =&gt; a - b})
		val rMean = sum(residuals) / residuals.size.toDouble
		val ssRes = sumSq(residuals.map(_ - rMean))

		1.0 - ssRes / (ssReg + ssRes)
	}

	def sq(in:Double) = in * in
	def sum(in: Array[Double]) = (0.0 /: in){_ + _}
	def sumSq(in: Array[Double]) = sum(in.map(sq))
</pre>
<p>The conciseness of Scala means that in reading the code, you can quickly discern both what a function does and how it does it. <em>ssReg</em>, for example is literally &#8220;the sum of the squares of pairs of items from <em>y</em> and <em>residuals</em> subtracted&#8221; or, more colloquially, &#8220;the sum of the squares of differences between <em>y</em> and <em>residuals</em> elements.</p>
]]></content:encoded>
			<wfw:commentRss>http://garyboone.com/2010/04/easy-multivariate-linear-regression-in-scala/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>SingletonApp: How to run only one application instance at a time in Scala</title>
		<link>http://garyboone.com/2010/02/singletonapp-how-to-allow-only-one-application-instance-at-a-time/</link>
		<comments>http://garyboone.com/2010/02/singletonapp-how-to-allow-only-one-application-instance-at-a-time/#comments</comments>
		<pubDate>Fri, 26 Feb 2010 04:48:00 +0000</pubDate>
		<dc:creator>gary</dc:creator>
				<category><![CDATA[Coding]]></category>
		<category><![CDATA[Scala]]></category>

		<guid isPermaLink="false">http://garyboone.com/2010/02/singletonapp-how-to-allow-only-one-application-instance-at-a-time/</guid>
		<description><![CDATA[Here&#8217;s a way to ensure that only one instance of your application runs at a time. Perhaps it updates a resource and you need to prevent duplicate updates. Or, in another use, I recently wanted to make sure an application was always running. So I wrote a cron job to periodically start the program; if [...]]]></description>
			<content:encoded><![CDATA[<p>Here&#8217;s a way to ensure that only one instance of your application runs at a time. Perhaps it updates a resource and you need to prevent duplicate updates. Or, in another use, I recently wanted to make sure an application was always running. So I wrote a cron job to periodically start the program; if it was already running, the new start failed.</p>
<p>A traditional method for ensure single instances of program uses file locking and PIDs. A program, upon start up, would get its process id (PID) from the OS, then write it to a file called &#8220;program.lock&#8221; in a known, fixed location. Then it would read the file and check the written PID against its own. If they match, great; continue. If they don&#8217;t match, it means that another file succeeded at creating the file, ie got the lock, so this application must shut down. You might think that if the file exists, then no check is necessary. However, the idea is to handle the situation when multiple instances start at nearly identical times. Neither sees the file and tries to create it, but only one succeeds because Unix file creation is atomic.</p>
<p>The traditional method is clever, but challenging to get right. Lock files must be removed on exit, requiring more code. If the program terminates unexpectedly, provisions must be made to catch the exit signal and clean up or use additional methods to reap leftover lockfiles.</p>
<p>Here&#8217;s a much simpler method. Like the traditional method, each application attempts to hold a shared resource. Only one succeeds, and the resource hold is automatically released on program termination. The resource? A OS network port. So the only risk is accidentally choosing a port needed by another application for actual communication.</p>
<p>All you have to do is choose a port to use as an &#8220;application exclusion group id&#8221;. Several applications use the id. But only one application among the group sharing the id can run at a time.</p>
<p>Here&#8217;s the code. Include the file in your program, then call <em>SingletonApp.performSolo</em> as shown in the demo. To demo, just run multiple copies of the file as shown in the comments. Only one will run at a time&#8230;</p>
<pre class="brush: scala;">
import java.net.BindException
import java.net.ServerSocket

/**
 * This class enables applications to ensure that only one instance
 * of the application runs at a time.
 *
 * @author  Gary Boone, PhD
 * @version 1.0, 2010/02/24
 */
object SingletonApp {

	var serverSocket:ServerSocket = null

	/**
	 * Pick a port number to use as the application exclusion
	 * group id. Choose a port that won't conflict with other
	 * applications. See
	 * http://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers
	 * for common port numbers.
	 *
	 * Additionally, pass in a closure to be run if the application
	 * is already running.
	 */
	def performSolo( portToHold:Int)( fail: =&gt; Unit ) = {
		try {
			serverSocket = new ServerSocket(portToHold)
		} catch {
		  	case e:BindException =&gt; fail
		}
	}

	/**
	 * Demo the SingletonApp class
	 *
	 * Compile, or run with:
	 * scala -i SingletonApp.scala -e 'SingletonApp.main(null)' &amp;
	 * Then start another instance to see it fail.
	 */
	def main( args:Array[String] ) : Unit = {
		val DEMO_PORT_TO_HOLD = 15486

		// ensure single instance
		SingletonApp.performSolo(DEMO_PORT_TO_HOLD) {
			println(&quot;failing due to already-running instance.&quot;)
			exit
		}

		println(&quot;Application started. Try to start another instance.&quot;)
		Thread.sleep(300000)		// 3e6 ms = 300 sec = 5 min
		println(&quot;exiting&quot;)
	}
}
</pre>
]]></content:encoded>
			<wfw:commentRss>http://garyboone.com/2010/02/singletonapp-how-to-allow-only-one-application-instance-at-a-time/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Fast Partial Sort in Scala</title>
		<link>http://garyboone.com/2009/11/fast-partial-sort-in-scala/</link>
		<comments>http://garyboone.com/2009/11/fast-partial-sort-in-scala/#comments</comments>
		<pubDate>Mon, 02 Nov 2009 22:05:22 +0000</pubDate>
		<dc:creator>gary</dc:creator>
				<category><![CDATA[Scala]]></category>

		<guid isPermaLink="false">http://garyboone.com/2009/11/fast-partial-sort-in-scala/</guid>
		<description><![CDATA[Sometimes you need the top k items in a list. A naive way to do it is to sort the list, then take the first k items. The problem with that approach is that you don&#8217;t need to sort the whole list, so it&#8217;s inefficient and becomes more so as the list length, n, increases [...]]]></description>
			<content:encoded><![CDATA[<p>Sometimes you need the top <em>k</em> items in a list. A naive way to do it is to sort the list, then take the first <em>k</em> items. The problem with that approach is that you don&#8217;t need to sort the whole list, so it&#8217;s inefficient and becomes more so as the list length, <em>n</em>, increases relative to <em>k</em>. </p>
<p>To sort just the top <em>k</em> items, you can use a bounded priority queue; after feeding the whole list into it, the queue contains the top <em>k</em> items. This approach is better, but expends unnecessary effort maintaining the sort in the queue as items are added. If <em>n</em> is much larger than <em>k</em>, it would be faster to find the top items without sorting, then sort only the final list of top items. </p>
<p>The code below does a partial sort in linear time. Upon return, the first <em>k</em> positions of the array contain the largest or smallest items of the array, depending on the <em>compare()</em> function provided by the Ordered trait of the class contained in the array. The items in the first <em>k</em> positions are not sorted.</p>
<pre class="brush: scala;">package scala

/*
 * FirstK
 *
 * These functions provide a linear partial sort of an array of Ordered objects. The array is
 * sorted in-place and upon return the the k smallest or largest items are in the first k positions.
 * The first k values are not sorted, but are less than or equal to the values in the rest of the
 * array. Whether the first k items are the largest or the smallest of the array is determined
 * by the compare function of the objects in the array.
 *
 * For example:
 * 	case class Foo(n: Int) extends Ordered[Foo] { def compare(other: Foo) = this.n.compare(other.n) }
 * means that firstK will return the smallest n values in Array[Foo]
 * 	case class Foo(n: Int) extends Ordered[Foo] { def compare(other: Foo) = -this.n.compare(other.n) }
 * means that firstK will return the largest n values in Array[Foo]
 *
 *  Example from scalatest unit test:
 *
 *    case class Foo(n: Int) extends Ordered[Foo] {
 *      def compare(other: Foo) = this.n.compare(other.n)
 *    }
 *
 * 	  test(&quot; Test findFirstK() Length 2&quot; ) {
 *      val array = Array(new Foo(2), new Foo(1))
 *      FirstK.findFirstK(array,  1)       // k = 1
 *      assert(array.deepEquals(Array(Foo(1), Foo(2))))
 *    }
 */
object FirstK {
	def swap[T](array: Array[T], x: Int, y: Int) = {
		val t = array(x)
		array(x) = array(y)
		array(y) = t
	}

	// Lomuto Partition
	def partition[T &lt;% Ordered[T]](array: Array[T], left: Int, right:Int, pivotIndex: Int): Int = {
		val pivotValue = array(pivotIndex)
		swap(array, pivotIndex, right)              // Move pivot to end
		var storeIndex = left
		for (i &lt;- left until right ) {
			if (array(i) &lt;= pivotValue) {			// will use the compare fn, so may use &gt; for desc sort
				swap(array, storeIndex, i)
				storeIndex += 1
			}
		}
		swap(array, right, storeIndex) 				// Move pivot to its final place
		storeIndex
	}

	// Note that p here is the position that ends the range of 'first' values.
	def findFirstToP[T &lt;% Ordered[T]](array: Array[T], left: Int, right:Int, p: Int): Unit = {
		if (right &gt; left) {
			val pivotIndex = (left + right) / 2
			val pivotNewIndex = partition(array, left, right, pivotIndex)
			if (pivotNewIndex &gt; p)
				findFirstToP(array, left, pivotNewIndex - 1, p)
			if (pivotNewIndex &lt; p)
				findFirstToP(array, pivotNewIndex + 1, right, p)
		}
	}

 	// intended entry fn; includes parameter checking. Modifies the array so that the first k items
 	// are largest/smallest of the array.
	def findFirstK[T &lt;% Ordered[T]](array: Array[T],  k: Int) : Unit = {
		if (array==null || k==0 || k&gt;array.size) {
			throw new IllegalArgumentException()
		}
		findFirstToP(array, 0, array.length - 1, k-1)		// fn is position-based so, k-1 for 'first k'
	}
}
</pre>
]]></content:encoded>
			<wfw:commentRss>http://garyboone.com/2009/11/fast-partial-sort-in-scala/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Effective Use of Options in Scala</title>
		<link>http://garyboone.com/2009/10/effective-use-of-options-in-scala/</link>
		<comments>http://garyboone.com/2009/10/effective-use-of-options-in-scala/#comments</comments>
		<pubDate>Fri, 02 Oct 2009 21:06:01 +0000</pubDate>
		<dc:creator>gary</dc:creator>
				<category><![CDATA[Scala]]></category>

		<guid isPermaLink="false">http://garyboone.com/2009/10/effective-use-of-options-in-scala/</guid>
		<description><![CDATA[If you&#8217;ve played around with the Option class, you know that it allows you to note that no value is available and do so without nulls. For example, using getOrElse() you can access a value or a default when no value is present:
scala> val a:Option[Int] = Some(5)a: Option[Int] = Some(5)scala> val b:Option[Int] = None b: [...]]]></description>
			<content:encoded><![CDATA[<p style="clear: both">If you&#8217;ve played around with the Option class, you know that it allows you to note that no value is available and do so without nulls. For example, using <em>getOrElse()</em> you can access a value or a default when no value is present:</p>
<blockquote style="clear: both"><p>scala> val a:Option[Int] = Some(5)<br />a: Option[Int] = Some(5)<br />scala> val b:Option[Int] = None <br />b: Option[Int] = None<br />scala> a.getOrElse(0)<br />res1: Int = 5<br />scala> b.getOrElse(0)<br />res2: Int = 0</p>
</blockquote>
<p style="clear: both">But a problem you&#8217;re likely to come across is how to access an <em>instance variable</em> when a <em>class</em> is stored in an option? For example, </p>
<blockquote style="clear: both"><p>scala> case class S(lines:Int, pages:Int)<br />defined class S<br />scala> val sOpt:Option[S] = Some(new S(16,5) )<br />sOpt: Option[S] = Some(S(16,5))<br />scala> val nOpt:Option[S] = None<br />nOpt: Option[S] = None</p>
</blockquote>
<p style="clear: both">Here, we&#8217;ve created a simple class an put an instance of it into an Option. Then we made another option container for the class containing <em>None</em>. So given an <em>Option[S]</em>, how do you get the <em>lines</em> value out of it? You can&#8217;t do it directly because the Option may contain <em>None</em>. </p>
<p style="clear: both">The answer is to use <em>map</em>, passing in the accessor or other function you want to apply. In this case, we just use the accessor <em>lines</em>. An Option is returned, so <em>getOrElse()</em> then returns the value or a default.</p>
<blockquote style="clear: both"><p>scala> val numLines = sOpt.map{ _.lines }.getOrElse(0)<br />numLines: Int = 16<br />scala> val numLines = nOpt.map{ _.lines }.getOrElse(0)<br />numLines: Int = 0</p>
</blockquote>
<p style="clear: both">The underscore is an abbreviation for the object in the map. Don&#8217;t forget that you can also pass functions into the map. </p>
<blockquote style="clear: both"><p>scala> sOpt.map{println} <br />S(16,5)<br />scala> nOpt.map{println}</p>
</blockquote>
<p style="clear: both">Not that the instance <em>toString()</em> was printed by the first line, whereas the second printed nothing because the Option contained a <em>None</em>. (I&#8217;ve omitted the REPL result lines.)</p>
<p style="clear: both">Finally, note that complex functions can be built using the normal block &#8220;=>&#8221; syntax. Here, we print as well as accessing the <em>lines</em> instance variable:</p>
<blockquote style="clear: both"><p>scala> val numLines = sOpt.map{x => println(x); x.lines}.getOrElse(0)<br />S(16,5)<br />numLines: Int = 16<br />scala> val numLines = nOpt.map{x => println(x); x.lines}.getOrElse(0)<br />numLines: Int = 0<br />scala> </p>
</blockquote>
<p style="clear: both">
<p style="clear: both">
<p><br class="final-break" style="clear: both" /></p>
]]></content:encoded>
			<wfw:commentRss>http://garyboone.com/2009/10/effective-use-of-options-in-scala/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>min and sum one-liners</title>
		<link>http://garyboone.com/2009/08/min-and-sum-one-liners/</link>
		<comments>http://garyboone.com/2009/08/min-and-sum-one-liners/#comments</comments>
		<pubDate>Fri, 21 Aug 2009 05:45:05 +0000</pubDate>
		<dc:creator>gary</dc:creator>
				<category><![CDATA[Scala]]></category>

		<guid isPermaLink="false">http://garyboone.com/2009/08/min-and-sum-one-liners/</guid>
		<description><![CDATA[
// Sum the values in a list
val sum = (0.0 /: list){ _ + _ }
// What it says: it's an abbreviated form of
// list.leftFold(0.0) { (s,i) =&#62; s + i }

// Find the minimum value in a list
val minValue = list.reduceLeft( _ min _ )
// What it says: Note that it's reduce, not fold. [...]]]></description>
			<content:encoded><![CDATA[<pre class="brush: scala;">
// Sum the values in a list
val sum = (0.0 /: list){ _ + _ }
// What it says: it's an abbreviated form of
// list.leftFold(0.0) { (s,i) =&gt; s + i }

// Find the minimum value in a list
val minValue = list.reduceLeft( _ min _ )
// What it says: Note that it's reduce, not fold. It applies the
// min function to the series of results obtained by applying
// the function from the left. 

// Note the difference between fold and reduce: fold takes an
// initial value, while reduce does not.
</pre>
]]></content:encoded>
			<wfw:commentRss>http://garyboone.com/2009/08/min-and-sum-one-liners/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Scala Eclipse Plugin Error: Scala Signature</title>
		<link>http://garyboone.com/2009/06/scala-eclipse-plugin-error-scala-signature/</link>
		<comments>http://garyboone.com/2009/06/scala-eclipse-plugin-error-scala-signature/#comments</comments>
		<pubDate>Thu, 25 Jun 2009 22:54:28 +0000</pubDate>
		<dc:creator>gary</dc:creator>
				<category><![CDATA[Scala]]></category>
		<category><![CDATA[configgy]]></category>
		<category><![CDATA[eclipse]]></category>

		<guid isPermaLink="false">http://garyboone.com/2009/06/scala-eclipse-plugin-error-scala-signature/</guid>
		<description><![CDATA[Trying to start a program created with the eclipse Scala plugin, I saw an error that the main class couldn&#8217;t be found. That was cryptic, as there was a main. Stranger still, this is a program I had run successfully before. 
The first part of solving the problem was to look for clues in the [...]]]></description>
			<content:encoded><![CDATA[<p style="clear: both">Trying to start a program created with the eclipse Scala plugin, I saw an error that the main class couldn&#8217;t be found. That was cryptic, as there was a main. Stranger still, this is a program I had run successfully before. </p>
<p style="clear: both">The first part of solving the problem was to look for clues in the <em>Problems</em> view. Opening it, I saw this:</p>
<blockquote style="clear: both"><p>error while loading Configgy, Scala signature Configgy has wrong version expected: 5.0 found: 4.1 in /Users/&#8230;</p>
</blockquote>
<p style="clear: both">So the first error was due to the compilation failing and not producing a main class that eclipse could launch.</p>
<p>After further digging, the version error turned out to be caused by a mismatch between the Scala version (2.7.5) I used to compile the Configgy library and the Scala version (2.8) that the eclipse plugin used to compile the rest of the program. I didn&#8217;t install Scala 2.8, so how could this occur? The Scala plugin installs its own version of Scala. Because I had selected the nightly build version of the plugin, the Scala versions drifted apart during one of the eclipse updates. </p>
<p style="clear: both">You can tell which version the eclipse Scala plugin uses by looking at the jar name in the <em>eclipse/plugins</em> directory. Eg, <em>scala.tools.nsc_2.75.final.jar</em></p>
<p style="clear: both">The solution was to revert to the stable, release version of the plugin. Do that by using this url in the eclipse <em>Software Updates</em> | <em>Available Software</em> | <em>Manage Sites&#8230;</em> list. </p>
<blockquote style="clear: both"><p>http://www.scala-lang.org/scala-eclipse-plugin</p>
</blockquote>
<p style="clear: both">More complete directions <a href="http://www.scala-lang.org/node/94">here</a>.</p>
<p><br class="final-break" style="clear: both" /></p>
]]></content:encoded>
			<wfw:commentRss>http://garyboone.com/2009/06/scala-eclipse-plugin-error-scala-signature/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Creating Single-file Runnable Jars in Scala with NetBeans</title>
		<link>http://garyboone.com/2009/06/creating-single-file-runnable-jars-in-scala-and-netbeans/</link>
		<comments>http://garyboone.com/2009/06/creating-single-file-runnable-jars-in-scala-and-netbeans/#comments</comments>
		<pubDate>Mon, 22 Jun 2009 07:12:32 +0000</pubDate>
		<dc:creator>gary</dc:creator>
				<category><![CDATA[Scala]]></category>
		<category><![CDATA[NetBeans]]></category>
		<category><![CDATA[runnable jar]]></category>

		<guid isPermaLink="false">http://garyboone.com/2009/06/creating-single-file-runnable-jars-in-scala-and-netbeans/</guid>
		<description><![CDATA[In NetBeans, creating a runnable jar for your Scala program is even easier. It&#8217;s done automatically when you build your project. The compile output even reminds you how to run the jar file.
The first time I did it, I saw an error about finding a Scala object. Solve that by adding the scala-library.jar to your [...]]]></description>
			<content:encoded><![CDATA[<p style="clear: both">In NetBeans, creating a runnable jar for your Scala program is even easier. It&#8217;s done automatically when you build your project. The compile output even reminds you how to run the jar file.</p>
<p style="clear: both">The first time I did it, I saw an error about finding a Scala object. Solve that by adding the <em>scala-library.jar</em> to your project. Right-click on the libraries folder in the Projects tab on the left sidebar. Choose <em>Add JAR/Folder</em> and find your <em>scala-library.jar</em>. Because I installed Scala with MacPorts, mine was under </p>
<p style="clear: both">
<blockquote style="clear: both"><p>/opt/local/var/macports/software/scala/2.7.4_0/opt/local/share/scala/lib</p>
</blockquote>
<p style="clear: both">
<p style="clear: both">See <a href="http://garyboone.com/2009/06/installing-scala-on-macs-via-macports/">this blog entry</a> for more on finding MacPorts installations.</p>
<p style="clear: both">
<p style="clear: both">Add any other required libaries this way. Rebuild. Then you can run your program via</p>
<p style="clear: both">
<blockquote style="clear: both"><p>$ java -jar YourProgram</p>
</blockquote>
<p style="clear: both">
<p style="clear: both">in the <em>dist/</em> directory.</p>
<p style="clear: both">
<p style="clear: both">Note that by default, the NetBeans jar mechanism creates a jar file for your program and then adds the libraries you specified into a <em>lib</em> directory. So it&#8217;s not a single executable jar. You can then zip and distribute the jar/directory. The advantage of this approach is that you can update the libraries in the lib directory without having to rejar everything. You can probably also save space by using symbolic links in the <em>lib</em> directory to point to your jar locations. I haven&#8217;t tried that, though.</p>
<p style="clear: both">
<p style="clear: both">You can ignore the lib directory by directly linking to your libraries in the java command using Xbootclasspath. Here, I&#8217;ve added two libraries, Configgy and the Scala jar, to my project, but note that I also had to include the path to the Java SDK:</p>
<p style="clear: both">
<blockquote style="clear: both"><p> java -Xbootclasspath:/opt/local/var/macports/software/scala/2.7.4_0/opt/local/share/scala/lib/scala-library.jar:../configgy/dist/configgy-1.3/configgy-1.3.jar:/System/Library/Frameworks/JavaVM.framework/Versions/1.6/Classes/classes.jar -jar ScalaApplication1.jar </p>
</blockquote>
<p style="clear: both">
<p style="clear: both">If you want to create a single jar with all of the required files, then add a few lines to your build.xml file. There are many varying pages on the web about this; I found these directions simplest:</p>
<p style="clear: both">
<p style="clear: both">1. Add</p>
<pre class="brush: plain;">
&lt;target name=&quot;-pre-jar&quot;&gt;
    &lt;unjar dest=&quot;${build.classes.dir}&quot; src=&quot;${file.reference.theLibraryName.jar}&quot;&gt;
&lt;/target&gt;
</pre>
<p style="clear: both">to the <em>build.xml</em> file, replacing theLibraryName with the appropriate jar filename.</p>
<p style="clear: both">2. Rebuild</p>
<p style="clear: both">
<p style="clear: both">To get the correct library filename, switch to the <em>Files</em> tab in the left sidebar and look in the <em>project.properties</em> file. Find lines that look like these:</p>
<pre class="brush: plain;">
&lt;unjar dest=&quot;${build.classes.dir}&quot; src=&quot;${file.reference.configgy-1.3.jar}&quot;/&gt;
&lt;unjar dest=&quot;${build.classes.dir}&quot; src=&quot;${file.reference.scala-library.jar}&quot;/&gt;
</pre>
<p style="clear: both">You can <em>ls -l</em> your program in the dist directory and see that it&#8217;s much larger; it now contains the libraries. The lib directory is still there, but you don&#8217;t need it anymore.</p>
<p><br class="final-break" style="clear: both" /></p>
]]></content:encoded>
			<wfw:commentRss>http://garyboone.com/2009/06/creating-single-file-runnable-jars-in-scala-and-netbeans/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Creating Single-file Runnable Jars in Scala with eclipse</title>
		<link>http://garyboone.com/2009/06/creating-single-file-runnable-jars-in-scala-and-eclipse/</link>
		<comments>http://garyboone.com/2009/06/creating-single-file-runnable-jars-in-scala-and-eclipse/#comments</comments>
		<pubDate>Mon, 22 Jun 2009 06:47:02 +0000</pubDate>
		<dc:creator>gary</dc:creator>
				<category><![CDATA[Scala]]></category>
		<category><![CDATA[eclipse]]></category>
		<category><![CDATA[runnable jar]]></category>

		<guid isPermaLink="false">http://garyboone.com/2009/06/creating-single-file-runnable-jars-in-scala-and-eclipse/</guid>
		<description><![CDATA[How do you create a single runnable jar that contains all the files it needs to run? This is one of those questions that should be easier to answer. Here&#8217;s how to do it in eclipse and NetBeans.
First, eclipse, following the post here:1. Create a Java class to run your Scala main:

package scala.loader;
import java.util.*;
public class [...]]]></description>
			<content:encoded><![CDATA[<p style="clear: both">How do you create a single runnable jar that contains all the files it needs to run? This is one of those questions that should be easier to answer. Here&#8217;s how to do it in eclipse and NetBeans.</p>
<p style="clear: both">First, eclipse, following the post <a href="http://www.artima.com/forums/flat.jsp?forum=282&#038;thread=245933">here</a>:<br />1. Create a Java class to run your Scala main:</p>
<pre class="brush: java;">
package scala.loader;
import java.util.*;
public class ScalaEntryPoint
{
    public static void main(String[] args) {
    List&lt;string&gt; argList = new ArrayList&lt;string&gt;();
    argList.add(&quot;YourScalaObjectWithMain&quot;);
    for (String s : args) argList.add(s);
        scala.tools.nsc.MainGenericRunner.main(argList.toArray(new String[0]));
    }
}
</pre>
<p style="clear: both">Be sure to change <em>YourScalaObjectWithMain</em> to your class. Also, you&#8217;ll have to add the Scala tools jar to your projects classpath: <em>Project</em> | <em>Properties</em> | <em>Java Build Path</em> tab | <em>Libraries</em> tab | <em>Add External Jars&#8230;</em> button. Then pick the <em>scala.tools.nsc</em> file in your eclipse/plugins folder.</p>
<p>2. Create a Run Configuration to run the Java class. Check that it runs.</p>
<p style="clear: both">3. Then choose <em>File</em> | <em>Export&#8230;,</em> then <em>Java</em> | <em>Runnable JAR File</em>, then pick the Java run configuration to export and a destination. Optionally, you can save the ant XML file that does the export. Later, after some edits, you can rejar using</p>
<blockquote style="clear: both"><p>ant -f yourjarXMLfile.xml</p>
</blockquote>
<p style="clear: both">If you change your libraries, be sure to repeat the complete Export process to make sure your jar scrips includes the correct jars.</p>
<p style="clear: both">
<p><br class="final-break" style="clear: both" /></p>
]]></content:encoded>
			<wfw:commentRss>http://garyboone.com/2009/06/creating-single-file-runnable-jars-in-scala-and-eclipse/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
	</channel>
</rss>

