<?xml version="1.0"?>
<feed xmlns="http://www.w3.org/2005/Atom" xmlns:planet="http://planet.intertwingly.net/" xmlns:indexing="urn:atom-extension:indexing" indexing:index="no"><access:restriction xmlns:access="http://www.bloglines.com/about/specs/fac-1.0" relationship="deny"/>
  <title>Planet Scala</title>
  <updated>2010-09-09T03:01:13Z</updated>
  <generator uri="http://intertwingly.net/code/venus/">Venus</generator>
  <author>
    <name>James Iry</name>
    <email>jamesiry@gmail.com</email>
  </author>
  <id>http://www.planetscala.com/atom.xml</id>
  <link href="http://www.planetscala.com/atom.xml" rel="self" type="application/atom+xml"/>
  <link href="http://www.planetscala.com" rel="alternate"/>

  <entry xml:lang="en">
    <id>http://ikaisays.com/?p=142</id>
    <link href="http://ikaisays.com/2010/09/08/gwt-blobstore-the-new-high-performance-image-serving-api-and-cute-dogs-on-office-chairs/" rel="alternate" type="text/html"/>
    <title>GWT, Blobstore, the new high performance image serving API, and cute dogs on office chairs</title>
    <summary type="xhtml"><div xmlns="http://www.w3.org/1999/xhtml">I’ve been working on an image sharing application using GWT and App Engine to familiarize myself with the newer aspects of GWT. The project and code are here: http://ikai-photoshare.appspot.com http://github.com/ikai/gwt-gae-image-gallery (Please excuse spaghetti code in client side GWT code, much of it was me feeling my way around GWT. I’ve come to appreciate GWT quite [...]<img alt="" border="0" height="1" src="http://stats.wordpress.com/b.gif?host=ikaisays.com&amp;blog=5969280&amp;post=142&amp;subd=ikailansays&amp;ref=&amp;feed=1" width="1"/></div>
    </summary>
    <content type="xhtml"><div xmlns="http://www.w3.org/1999/xhtml"><p>I’ve been working on an image sharing application using GWT and App Engine to familiarize myself with the newer aspects of GWT. The project and code are here:</p>
<p><a href="http://ikai-photoshare.appspot.com">http://ikai-photoshare.appspot.com</a><br/>
<a href="http://github.com/ikai/gwt-gae-image-gallery">http://github.com/ikai/gwt-gae-image-gallery</a></p>
<p>(Please excuse spaghetti code in client side GWT code, much of it was me feeling my way around GWT. I’ve come to appreciate GWT quite a bit in spite of the fact that I’m pretty familiar with client side development; I’ll write about this in a future post).</p>
<p>The <a href="http://googleappengine.blogspot.com/2010/08/multi-tenancy-support-high-performance_17.html">1.3.6 release</a> of the App Engine SDK shipped with a high performance image serving API. What this means is that a developer can take a blob key pointing to image data stored in the <a href="http://code.google.com/appengine/docs/java/blobstore/">blobstore</a> and call getServingUrl() to create a special URL for serving the image. What are the benefits to using this API?</p>
<ul>
<li>You don’t have to write your own <a href="http://code.google.com/appengine/articles/java/serving_dynamic_images.html">handler for uploaded images</a></li>
<li>You don’t have to consume storage quota for saving resized or cropped images, as you can perform transforms on the image simply by appending URL parameters. You only need to store the final URL that is generated by getServingUrl().</li>
<li>You aren’t charged for datastore CPU for fetching the image (you will still be billed for bandwidth)</li>
<li>Images are, in general, served from edge server locations which can be geographically located closer to the user</li>
</ul>
<p>There are a few drawbacks, however, to using the API:</p>
<ul>
<li>There aren’t any great schemes for access control of the images, and if someone has the URL for a thumbnail, they can easily remove the parameters to see a larger image</li>
<li>Billing must be enabled – you will only be charged for usage, however, so you don’t have to spend a cent to use the API. You just have to have billing active.</li>
<li>Deleting an image blob doesn’t delete the image being served from the URL right away – that image will still be available for some time</li>
<li>Images must be uploaded to the blobstore, not the datastore as a blob, so it’s important to understand how the blobstore API works</li>
<li>The URLs of the created images are really, really ugly. If you need pretty URLs, it’s probably a better pattern to create a URL mapping to an HTML page that just displays the image in an IMG tag</li>
</ul>
<h2>Blobstore crash course</h2>
<p>It’ll be best if we gave a quick refresher course on the blobstore before we begin. Here’s the standard flow for a blobstore upload:</p>
<ol>
<li> Create a new blobstore session and generate an upload URL for a form to POST to. This is done using the <a href="http://code.google.com/appengine/docs/java/javadoc/com/google/appengine/api/blobstore/BlobstoreService.html#createUploadUrl(java.lang.String)">createUploadUrl() method of BlobstoreService</a>. Pass a callback URL to this method. This URL is where the user will be forwarded after the upload has completed.</li>
<li>Present an upload form to the user. The action is the URL generated in step 1. Each URL must be unique: you cannot use the same URL for multiple sessions, as this will cause an error.</li>
<li>After the URL has uploaded the file, the user is forwarded to the callback URL in your App Engine application specified in step 1. The key of the uploaded blob, a String blob key, is passed as an URL parameter. Save this URL and pass the user to their final destination</li>
</ol>
<p>Got it? Now we can talk about image serving.</p>
<h2>Using the image serving URL</h2>
<p>Once we have a blob key (step 3 of a Blobstore upload), we can do interesting things with it. First, we’ll need to create an instance of the ImagesService:</p>
<pre class="brush: java;">ImagesService imagesService = ImagesServiceFactory.getImagesService();
</pre>
<p>Once we have an instance, we pass the blob key to getServingUrl and get back a URL:</p>
<pre class="brush: java;">String imageUrl = imagesService.getServingUrl(blobKey);
</pre>
<p>This can sometimes take several hundred milliseconds to a few seconds to generate, so it’s almost always a good idea to run this on write as opposed to first read. Subsequent calls should be faster, but they may not be as fast as reading this value from a datastore entity property or memcache. Since this value doesn’t change, it’s a good idea to store it. On the local dev server, this URL looks something like this:</p>
<p/><pre>/_ah/img/eq871HJL_bYxhWQbTeYYoA</pre>
<p/>
<p>In production, however, this will return a URL that looks like this:</p>
<p/><pre>http://lh5.ggpht.com/2PQk0vDo8Bn8oiPba2gtGlDfd1ciD0H0MLrixcT12FCDQEm2oyMW9ErJX_-ZzOHBWbYBKzevK0BY6cxdZ3cxf_37</pre>
<p>(Cute dogs below)<br/>
<img src="http://lh5.ggpht.com/2PQk0vDo8Bn8oiPba2gtGlDfd1ciD0H0MLrixcT12FCDQEm2oyMW9ErJX_-ZzOHBWbYBKzevK0BY6cxdZ3cxf_37=s500"/>
</p>
<p>You’ve already saved yourself the trouble of writing a handler. What’s really nice about this URL is that you can perform operations on it just by appending parameters. Let’s say we wanted to crop our image to be no larger than 200×200, yet retain scale. We’d simply append “=s200” to the end of the image:</p>
<p/><pre>http://lh5.ggpht.com/2PQk0vDo8Bn8oiPba2gtGlDfd1ciD0H0MLrixcT12FCDQEm2oyMW9ErJX_-ZzOHBWbYBKzevK0BY6cxdZ3cxf_37=s144</pre>
<p>(Looks like this)<br/>
<img alt="" src="http://lh5.ggpht.com/2PQk0vDo8Bn8oiPba2gtGlDfd1ciD0H0MLrixcT12FCDQEm2oyMW9ErJX_-ZzOHBWbYBKzevK0BY6cxdZ3cxf_37=s144"/></p>
<p>We can also crop the image by appending a “-c” to the size parameter:</p>
<pre>http://lh5.ggpht.com/2PQk0vDo8Bn8oiPba2gtGlDfd1ciD0H0MLrixcT12FCDQEm2oyMW9ErJX_-ZzOHBWbYBKzevK0BY6cxdZ3cxf_37=s144-c</pre>
<p>(Looks like this – compare with above)</p>
<p><img alt="" src="http://lh5.ggpht.com/2PQk0vDo8Bn8oiPba2gtGlDfd1ciD0H0MLrixcT12FCDQEm2oyMW9ErJX_-ZzOHBWbYBKzevK0BY6cxdZ3cxf_37=s144-c"/></p>
<p>Note that we can also generate these URLs programmatically using the <a href="http://code.google.com/appengine/docs/java/javadoc/com/google/appengine/api/images/ImagesService.html#getServingUrl(com.google.appengine.api.blobstore.BlobKey, int, boolean)">overloaded version of getServingUrl</a> that also accepts a size and crop parameter.</p>
<h2>Adding GWT</h2>
<p>So now that we’ve got all that done, let’s get it working with GWT. It’s important that we understand how it all works, because GWT’s single-page, Javascript-generated content model must be taken into account. Let’s draw our upload widget. We’ll be using UiBinder:</p>
<p>We’ll create our Composite class as follows:</p>
<pre class="brush: java;">public class UploadPhoto extends Composite {

    private static UploadPhotoUiBinder uiBinder = GWT.create(UploadPhotoUiBinder.class);

    UserImageServiceAsync userImageService = GWT.create(UserImageService.class);

    interface UploadPhotoUiBinder extends UiBinder {}

    @UiField
    Button uploadButton;

    @UiField
    FormPanel uploadForm;

    @UiField
    FileUpload uploadField;

    public UploadPhoto(final LoginInfo loginInfo) {
        initWidget(uiBinder.createAndBindUi(this));
    }

}
</pre>
<p>Here’s the corresponding XML file:</p>
<pre class="brush: xml;">&lt;!DOCTYPE ui:UiBinder SYSTEM "http://dl.google.com/gwt/DTD/xhtml.ent"&gt;
&lt;ui:UiBinder xmlns:ui="urn:ui:com.google.gwt.uibinder"
	xmlns:g="urn:import:com.google.gwt.user.client.ui"&gt;
	&lt;g:FormPanel ui:field="uploadForm"&gt;
		&lt;g:HorizontalPanel&gt;
			&lt;g:FileUpload ui:field="uploadField"&gt;&lt;/g:FileUpload&gt;
			&lt;g:Button ui:field="uploadButton"&gt;&lt;/g:Button&gt;
		&lt;/g:HorizontalPanel&gt;
	&lt;/g:FormPanel&gt;
&lt;/ui:UiBinder&gt;
</pre>
<p>(We’ll add more to this later)</p>
<p>When we discussed the Blobstore, we mentioned that each upload form has a different POST location corresponding to the upload session. We’ll have to add a GWT-RPC component to generate and return a URL. Let’s do that now:</p>
<pre class="brush: java;">// UserImageService.java
@RemoteServiceRelativePath("images")
public interface UserImageService extends RemoteService  {
    public String getBlobstoreUploadUrl();
}
</pre>
<p>Our IDE will nag us to generate the corresponding Async interface if we have a GWT plugin:</p>
<pre class="brush: java;">// UserImageServiceAsync.java
public interface UserImageServiceAsync {
    public void getBlobstoreUploadUrl(AsyncCallback callback);
}
</pre>
<p>We’ll need to write the code on the server side:</p>
<pre class="brush: java;">// UserImageServiceImpl.java
@SuppressWarnings("serial")
public class UserImageServiceImpl extends RemoteServiceServlet implements UserImageService {

    @Override
    public String getBlobstoreUploadUrl() {
        BlobstoreService blobstoreService = BlobstoreServiceFactory.getBlobstoreService();
        return blobstoreService.createUploadUrl("/upload");
    }

}
</pre>
<p>This is pretty straightforward. We’ll want to invoke this service on the client side when we build the form. Let’s add this to UploadPhoto:</p>
<pre class="brush: java;">public class UploadPhoto extends Composite {

private static UploadPhotoUiBinder uiBinder = GWT.create(UploadPhotoUiBinder.class);
UserImageServiceAsync userImageService = GWT.create(UserImageService.class);

interface UploadPhotoUiBinder extends UiBinder {}

    @UiField
    Button uploadButton;

    @UiField
    FormPanel uploadForm;

    @UiField
    FileUpload uploadField;

    public UploadPhoto() {
        initWidget(uiBinder.createAndBindUi(this));

        // Disable the button until we get the URL to POST to
        uploadButton.setText("Loading...");
        uploadForm.setEncoding(FormPanel.ENCODING_MULTIPART);
        uploadForm.setMethod(FormPanel.METHOD_POST);
        uploadButton.setEnabled(false);
        uploadField.setName("image");

        // Now we use out GWT-RPC service and get an URL
        startNewBlobstoreSession();

        // Once we've hit submit and it's complete, let's set the form to a new session.
        // We could also have probably done this on the onClick handler
        uploadForm.addSubmitCompleteHandler(new FormPanel.SubmitCompleteHandler() {

            @Override
            public void onSubmitComplete(SubmitCompleteEvent event) {
                uploadForm.reset();
               startNewBlobstoreSession();
            }
        });
    }

    private void startNewBlobstoreSession() {
        userImageService.getBlobstoreUploadUrl(new AsyncCallback() {

            @Override
            public void onSuccess(String result) {
                uploadForm.setAction(result);
                uploadButton.setText("Upload");
                uploadButton.setEnabled(true);
            }

            @Override
            public void onFailure(Throwable caught) {
                // We probably want to do something here
            }
        });
    }

    @UiHandler("uploadButton")
    void onSubmit(ClickEvent e) {
        uploadForm.submit();
    }

}
</pre>
<p>This is fairly standard <a>GWT RPC</a>.</p>
<p>So that concludes the GWT part of it. We mentioned an upload callback. Let’s implement that now:</p>
<pre class="brush: java;">/**
 * @author Ikai Lan
 *
 *         This is the servlet that handles the callback after the blobstore
 *         upload has completed. After the blobstore handler completes, it POSTs
 *         to the callback URL, which must return a redirect. We redirect to the
 *         GET portion of this servlet which sends back a key. GWT needs this
 *         Key to make another request to get the image serving URL. This adds
 *         an extra request, but the reason we do this is so that GWT has a Key
 *         to work with to manage the Image object. Note the content-type. We
 *         *need* to set this to get this to work. On the GWT side, we'll take
 *         this and show the image that was uploaded.
 *
 */
@SuppressWarnings("serial")
public class UploadServlet extends HttpServlet {
	private static final Logger log = Logger.getLogger(UploadServlet.class
			.getName());

	private BlobstoreService blobstoreService = BlobstoreServiceFactory
			.getBlobstoreService();

	public void doPost(HttpServletRequest req, HttpServletResponse res)
			throws ServletException, IOException {

		Map blobs = blobstoreService.getUploadedBlobs(req);
		BlobKey blobKey = blobs.get("image");

		if (blobKey == null) {
			// Uh ... something went really wrong here
		} else {

			ImagesService imagesService = ImagesServiceFactory
					.getImagesService();

			// Get the image serving URL
			String imageUrl = imagesService.getServingUrl(blobKey);

			// For the sake of clarity, we'll use low-level entities
			Entity uploadedImage = new Entity("UploadedImage");
			uploadedImage.setProperty("blobKey", blobKey);
			uploadedImage.setProperty(UploadedImage.CREATED_AT, new Date());

			// Highly unlikely we'll ever filter on this property
			uploadedImage.setUnindexedProperty(UploadedImage.SERVING_URL,
					imageUrl);

			DatastoreService datastore = DatastoreServiceFactory
					.getDatastoreService();
			datastore.put(uploadedImage);

			res.sendRedirect("/upload?imageUrl=" + imageUrl);
		}
	}

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {

		String imageUrl = req.getParameter("imageUrl");
		resp.setHeader("Content-Type", "text/html");

		// This is a bit hacky, but it'll work. We'll use this key in an Async
		// service to
		// fetch the image and image information
		resp.getWriter().println(imageUrl);

	}
}
</pre>
<p>We’ll probably want to display the image we just uploaded in the client. Let’s add a line line of code to register a SubmitCompleteHandler to do this:</p>
<pre class="brush: java;">	public void onSubmitComplete(SubmitCompleteEvent event) {
		uploadForm.reset();
		startNewBlobstoreSession();

		// This is what gets the result back - the content-type *must* be
		// text-html
		String imageUrl = event.getResults();
		Image image = new Image();
		image.setUrl(imageUrl);

		final PopupPanel imagePopup = new PopupPanel(true);
		imagePopup.setWidget(image);

		// Add some effects
		imagePopup.setAnimationEnabled(true); // animate opening the image
		imagePopup.setGlassEnabled(true); // darken everything under the image
		imagePopup.setAutoHideEnabled(true); // close image when the user clicks
												// outside it
		imagePopup.center(); // center the image

	}
</pre>
<p>And we’re done!</p>
<h2>Get the code</h2>
<p>I’ve got the code for this project here:</p>
<p><a href="http://github.com/ikai/gwt-gae-image-gallery">http://github.com/ikai/gwt-gae-image-gallery</a></p>
<p>Just a warning, this is a bit different from the sample code above. I wrote this post after I wrote the code, extrapolating the bare minimum to make this work. The sample code above has experimental tagging, delete and catches logins. I’m adding features to it simply to see what else can be done, so expect changes. I’m aware of a few of the bugs with the code, and I’ll get around to fixing them, but again, it’s a demo project, so keep realistic expectations. As far as I can tell, however, the code above should be runnable locally and deployable (once you have enabled billing for blobstore).</p>
<p>Happy developing!</p>
<br/>  <a href="http://feeds.wordpress.com/1.0/gocomments/ikailansays.wordpress.com/142/" rel="nofollow"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/ikailansays.wordpress.com/142/"/></a> <a href="http://feeds.wordpress.com/1.0/godelicious/ikailansays.wordpress.com/142/" rel="nofollow"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/ikailansays.wordpress.com/142/"/></a> <a href="http://feeds.wordpress.com/1.0/gofacebook/ikailansays.wordpress.com/142/" rel="nofollow"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/ikailansays.wordpress.com/142/"/></a> <a href="http://feeds.wordpress.com/1.0/gotwitter/ikailansays.wordpress.com/142/" rel="nofollow"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/ikailansays.wordpress.com/142/"/></a> <a href="http://feeds.wordpress.com/1.0/gostumble/ikailansays.wordpress.com/142/" rel="nofollow"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/ikailansays.wordpress.com/142/"/></a> <a href="http://feeds.wordpress.com/1.0/godigg/ikailansays.wordpress.com/142/" rel="nofollow"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/ikailansays.wordpress.com/142/"/></a> <a href="http://feeds.wordpress.com/1.0/goreddit/ikailansays.wordpress.com/142/" rel="nofollow"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/ikailansays.wordpress.com/142/"/></a> <img alt="" border="0" height="1" src="http://stats.wordpress.com/b.gif?host=ikaisays.com&amp;blog=5969280&amp;post=142&amp;subd=ikailansays&amp;ref=&amp;feed=1" width="1"/></div>
    </content>
    <updated>2010-09-09T01:00:02Z</updated>
    <category term="App Engine"/>
    <category term="Java"/>
    <author>
      <name>Ikai Lan</name>
    </author>
    <source>
      <id>http://ikaisays.com</id>
      <logo>http://0.gravatar.com/blavatar/4820fec29ccabd5dd64221099916101b?s=96&amp;d=http://s2.wp.com/i/buttonw-com.png</logo>
      <link href="http://ikaisays.com/feed/" rel="self" type="application/atom+xml"/>
      <link href="http://ikaisays.com" rel="alternate" type="text/html"/>
      <link href="http://ikaisays.com/osd.xml" rel="search" type="application/opensearchdescription+xml"/>
      <link href="http://ikaisays.com/?pushpress=hub" rel="hub" type="text/html"/>
      <subtitle>Follow me on Twitter: http://www.twitter.com/ikai</subtitle>
      <title>Ikai Lan says</title>
      <updated>2010-09-09T03:01:11Z</updated>
    </source>
  </entry>

  <entry>
    <id>tag:blogger.com,1999:blog-7045524330253482541.post-8294051801503348978</id>
    <link href="http://jim-mcbeath.blogspot.com/feeds/8294051801503348978/comments/default" rel="replies" type="application/atom+xml"/>
    <link href="https://www.blogger.com/comment.g?blogID=7045524330253482541&amp;postID=8294051801503348978" rel="replies" type="text/html"/>
    <link href="http://www.blogger.com/feeds/7045524330253482541/posts/default/8294051801503348978" rel="edit" type="application/atom+xml"/>
    <link href="http://www.blogger.com/feeds/7045524330253482541/posts/default/8294051801503348978" rel="self" type="application/atom+xml"/>
    <link href="http://jim-mcbeath.blogspot.com/2010/09/scala-generators.html" rel="alternate" type="text/html"/>
    <title>Scala Generators</title>
    <content type="xhtml"><div xmlns="http://www.w3.org/1999/xhtml">An implementation of generators on top of
Scala's delimited continuations.

<br/><br/>
In my
<a href="http://jim-mcbeath.blogspot.com/2010/09/scala-coroutines.html">
previous post</a>
I described a library that supports coroutines on top of Scala's
<a href="http://jim-mcbeath.blogspot.com/2010/08/delimited-continuations.html">
delimited continuations</a>
capability.
In this post I show how you can easily create generators on top of
that
<a href="http://www.github.com/jimmc/scoroutine">
coroutine library</a> (net.jimmc.scoroutine).
This is a second example of the kind of interesting construct
that can be built on top of Scala's delimited continuations.

<br/><br/>
As with my previous post on coroutines,
you don't need to understand <code>reset</code> and <code>shift</code>
if you just want to use the <code>Generator</code> class shown here
to write and use your own generators.
But, as with coroutines,
you should have a basic understanding of CPS code and its
<a href="http://jim-mcbeath.blogspot.com/2010/08/delimited-continuations.html#control_construct_restrictions">restrictions</a>
when writing generators.

<h3>Contents</h3>

<ul>
<li><a href="http://jim-mcbeath.blogspot.com/feeds/posts/default#generators">Generators</a>
</li><li><a href="http://jim-mcbeath.blogspot.com/feeds/posts/default#intgen">Integers Generator</a>
</li><li><a href="http://jim-mcbeath.blogspot.com/feeds/posts/default#primegen">Primes Generator</a>
</li><li><a href="http://jim-mcbeath.blogspot.com/feeds/posts/default#samefringe">Same Fringe</a>
</li><li><a href="http://jim-mcbeath.blogspot.com/feeds/posts/default#morepossibilities">More Possibilities</a>
</li></ul>

<a name="generators"/>
<h3>Generators</h3>

A <a href="http://en.wikipedia.org/wiki/Generator_%28computer_science%29">
generator</a>
is a routine that produces values like an iterator but is structured
as a function.
The generated values are returned by calling a special function,
typically called <code>yield</code>, with each value that is generated.
In our case, since <code>yield</code> is a reserved word in Scala,
we will use <code>yld</code> instead.

<br/><br/>
Generators and coroutines are
<a href="http://en.wikipedia.org/wiki/Coroutine#Coroutines_and_generators">
closely related</a>.
Depending on the implementation, generators and coroutines may be
almost the same thing or fairly different,
but in any case,
if you have either one, you can implement the other one on top of it.
Since we already have coroutines
in the <code>net.jimmc.scoroutine</code> library
described in my
<a href="http://jim-mcbeath.blogspot.com/2010/09/scala-coroutines.html">
previous post</a>,
we will implement generators on top of coroutines using that library.

<br/><br/>
You can think of this approach as using the Producer-Consumer pattern,
where we set up a generator as the producer and we allow the main
code to act as the consumer.
We create a generic <code>Generator</code> class that does the following:
<ul>
<li>Creates a <code>CoScheduler</code> that we use to control
    the generator.
</li><li>Creates a <code>CoQueue</code> buffer into which we will place
    the generated values.
</li><li>Provides convenience functions
    <code>yld</code> (in place of the reserved word <code>yield</code>)
    and <code>generate</code>.
</li><li>Provides <code>next</code> and <code>hasNext</code> functions for
    the consuming code to call from a non-CPS context,
    and so that a <code>Generator</code> can be used as an
    <code>Iterator</code>.
</li></ul>

This is all simple and straightforward.
Here is the code for
<a href="http://github.com/jimmc/scoroutine/tree/master/src/main/scala/net/jimmc/scoroutine/Generator.scala"><code>Generator</code></a>:

<br/><br/>
<input id="hlButton" type="submit" value="Highlight Syntax"/>
<pre class="scala" name="hlcode">package net.jimmc.scoroutine

import scala.collection.Iterator
import scala.util.continuations._

/** Generic generator class.
 */
class Generator[T] extends Iterator[T] {
    val sched = new DefaultCoScheduler
    val buf = new CoQueue[T](sched,1)

    /** Subclass calls this method to generate values.
     * @param body The code for your generator.
     */
    def generate(body: =&gt; Unit @suspendable) {
        sched.addRoutine("gen") { body }
        sched.run
    }

    /** Yield the next generated value.
     * Call this code from your generator to deliver the next value.
     */
    protected def yld(x:T):Unit @suspendable = {
        buf.blockingEnqueue(x)
    }

    /** Retrieve the next generated value.
     * Call this from your main code.
     */
    def next:T = {
        sched.run
        buf.dequeue
    }

    /** True if there is another value to retrieve.
     * Call this from your main code.
     */
    def hasNext:Boolean = {
        sched.run
        !buf.dequeueBlocker.isBlocked
    }
}
</pre>

We are not concerning ourselves with performance here, so we are simply
using the available <code>DefaultCoScheduler</code> as our scheduler.
As a future optimization, we could develop a scheduler optimized for
a single coroutine and use that as our scheduler for simple generators
that fit that criterion.
We could go further and use neither a scheduler nor <code>CoQueue</code>,
packaging all of the functionality directly into the <code>Generator</code>
class; but we are using the more expedient approach of using those two
pieces, since we already have them and are familiar with their use from
our experience with coroutines.

<a name="intgen"/>
<h3>Integers Generator</h3>

Here is how we would use our generic <code>Generator</code> class to create
a generator that will generate integers up to a specified maximum value:

<pre class="scala" name="hlcode">import net.jimmc.scoroutine.Generator

class IntGen(max:Int) extends Generator[Int] {
    generate {
        var x = 1
        while (x&lt;=max) {
            yld(x)
            x = x + 1
        }
    }
}
</pre>

The one catch to remember here is that the body of the <code>generate</code>
call is CPS code, so as with the body of a coroutine,
there are some <a href="http://jim-mcbeath.blogspot.com/2010/08/delimited-continuations.html#control_construct_restrictions">restrictions</a>
on what control constructs we can use.
Thus we use a <code>while</code> loop with a <code>var</code>
rather than a <code>for</code> loop, since the latter does not
yet work with the continuations compiler plugin.

<br/><br/>
Given the above generator class, here is a simple
<a href="http://github.com/jimmc/scoroutine/tree/master/src/example/scala/GenInts.scala"><code>GenInts</code></a>
object with a <code>main</code> function
that creates an instance of that generator,
then calls it to print out its values:

<pre class="scala" name="hlcode">object GenInts {
    def main(args:Array[String]) = {
        val gen = new IntGen(4)
        for (i &lt;- gen)
            println(i)
    }
}
</pre>

Alternatively, we could replace the <code>for</code> loop with direct
calls to <code>hasNext</code> and <code>next</code>:

<pre class="scala" name="hlcode">object GenInts {
    def main(args:Array[String]) = {
        val gen = new IntGen(4)
        while (gen.hasNext)
            println(gen.next)
    }
}
</pre>

<a name="primegen"/>
<h3>Primes Generator</h3>

It is
<a href="http://stackoverflow.com/questions/2201882/implementing-yield-yield-return-using-scala-continuations/2215182">
possible</a> to
<a href="http://stackoverflow.com/questions/2137619/scala-equivalent-to-python-generators">
use</a> <code>shift</code> and <code>reset</code> directly
to code up a generator,
but because our coroutine library implements a scheduler
to which new coroutines can be added at any time,
this gives you the ability to create generators that include
dynamic filter pipelines.

<br/><br/>
The example I use for this is the
<a href="http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes">
Sieve of Eratosthenes</a>,
a method of calculating primes in which,
each time a prime is found, it is added to a list of prime divisors
that are used for testing each new candidate.
In this
<a href="http://github.com/jimmc/scoroutine/tree/master/src/example/scala/GenPrimes.scala"><code>GenPrimes</code></a>
example, I create a new filter for each prime and add it to the pipeline.
You can do this much more efficiently in Scala
<a href="http://en.literateprograms.org/Sieve_of_Eratosthenes_%28Scala%29">
using a Stream</a>,
but this example illustrates the technique of dynamically building a pipeline
within a generator.

<pre class="scala" name="hlcode">import scala.util.continuations._

import net.jimmc.scoroutine.CoQueue
import net.jimmc.scoroutine.Generator

object GenPrimes {
    def main(args:Array[String]) = {
        val gen = new PrimeGen()
        for (i &lt;- gen) {
            println("Prime: "+i)
        }
    }
}

class PrimeGen extends Generator[Int] {
    val bufSize = 1
    val out1 = new CoQueue[Int](sched,bufSize)

    sched.addRoutine("prime2")(nextPrime(2,out1))
    generate {
        def gen(n:Int):Unit @suspendable = {
            out1.blockingEnqueue(n)
            gen(n+1)
        }
        gen(2)
    }

    def nextPrime(p:Int, in:CoQueue[Int]):Unit @suspendable = {
        var out:Option[CoQueue[Int]] = None
        yld(p)
        def sieve():Unit @suspendable = {
            val n = in.blockingDequeue()
            if ((n%p)!=0) {
                if (!out.isDefined) {
                    out = Some(new CoQueue[Int](sched,bufSize))
                    val rName = "prime"+n
                    sched.addRoutine(rName)(nextPrime(n,out.get))
                }
                out.get.blockingEnqueue(n)
            } else {
                in.dequeueBlocker.waitUntilNotBlocked
            }
            sieve()
        }
        sieve()
    }
}
</pre>

This example starts by setting up two coroutines:
the <code>addRoutine</code> call sets up the first filter in the pipeline,
which reads values from the <code>out1</code> queue and
filters our all numbers divisible by 2.
The <code>generator</code> call sets up the other initial coroutine,
which generates every integer and feeds it into the first filter in
the pipeline.
We start off this counting generator with the first prime number, 2.

<br/><br/>
The <code>nextPrime</code> function is called each time we see a new prime.
It starts by outputting its prime parameter value <code>p</code>
as a value of the GenPrimes generator.
It then goes into a loop reading its input buffer and looking for values
which are not divisible by its prime number.
The first time it finds one (when <code>out</code> is not yet defined)
it registers (with a call to <code>addRoutine</code>)  a new coroutine
based on a new instance of <code>nextPrime</code> that uses our output
as its input.
It then passes each candidate prime along to that next filter in
the sieve pipeline.

<br/><br/>
You can tell this is CPS code because of the <code>suspendable</code>
annotations, which is a cue to realizing
that the code might not behave quite as you think.
For example, the <code>gen</code> function within the body of the
<code>generate</code> call is recursive, so you might think it would
cause a stack overflow.
But since we are in a CPS function and the call to <code>blockingEnqueue</code>
is a call to a CPS function, the recursive call to <code>gen</code>
is turned into a continuation and executed later from the scheduler,
so it is in fact not recursive.
Likewise the recursive call to <code>sieve</code> is not really
recursive for the same reason.

<br/><br/>
Another CPS detail is the call to <code>waitUntilNotBlocked</code>.
It would seem to be functionally unnecessary, since the first thing
in the <code>sieve</code> function is a call to <code>blockingDequeue</code>.
However, this is the same attempt to avoid blocking as discussed in my
<a href="http://jim-mcbeath.blogspot.com/2010/09/scala-coroutines.html#attempt-to-avoid-blocking">previous post</a>;
without this call our code will not work.

<a name="samefringe"/>
<h3>Same Fringe</h3>

The
<a href="http://c2.com/cgi/wiki?SameFringeProblem">SameFringe</a>
problem has
<a href="http://www.crystalclearsoftware.com/soc/coroutine/coroutine/stackful.html#id2607744">
been called</a> the "killer application" for coroutines.
Given two trees, they have the same fringe if the leaves of the two
trees, read from left to right, are the same.

<br/><br/>
With coroutines, or in this case generators,
 the simple solution to this problem
is to create a generator that takes a tree and returns the sequence
of leaves of that tree,
then compare the outputs of two of those generators on the two trees
to be compared.

<br/><br/>
We start with a simple tree definition:

<pre class="scala" name="hlcode">sealed abstract class Tree[T]
case class Branch[T](left:Tree[T], right:Tree[T]) extends Tree[T]
case class Leaf[T](x:T) extends Tree[T]
</pre>

Given this tree definition, we write a generator that walks a tree
and yields all of the leaves:

<pre class="scala" name="hlcode">import scala.util.continuations._
import net.jimmc.scoroutine.Generator

class TreeFringe[T](tree:Tree[T]) extends Generator[T] {
    generate {
        def walk(t:Tree[T]):Unit @suspendable = {
            t match {
                case Leaf(x) =&gt; yld(x)
                case Branch(left,right) =&gt; walk(left); walk(right)
            }
        }
        walk(tree)
    }
}
</pre>

Since our generators implement the
<a href="http://www.scala-lang.org/api/current/scala/collection/Iterator.html">
<code>Iterator</code></a> trait, we can compare
two generators as two iterators with this little piece of code,
making the assumption that the tree leaf values are never null:

<pre class="scala" name="hlcode">    def sameFringe[T](tree1:Tree[T], tree2:Tree[T]):Boolean = {
        !((new TreeFringe(tree1)).zipAll(new TreeFringe(tree2),null,null).
            exists(p=&gt;p._1!=p._2))
    }
</pre>

Alternatively, we could use this more verbose version:

<pre class="scala" name="hlcode">    def sameFringe[T](tree1:Tree[T], tree2:Tree[T]):Boolean = {
        val fringe1 = new TreeFringe(tree1)
        val fringe2 = new TreeFringe(tree2)
        while(fringe1.hasNext &amp;&amp; fringe2.hasNext) {
            if (fringe1.next != fringe2.next)
                return false;
        }
        !(fringe1.hasNext || fringe2.hasNext)
    }
</pre>

We add a
<a href="http://github.com/jimmc/scoroutine/tree/master/src/example/scala/SameFringe.scala"><code>SameFringe</code></a> object with a
main method that creates some test trees, prints out
the leaves of each tree using our generator, then calls our
<code>sameFringe</code> method to check for equality.

<pre class="scala" name="hlcode">object SameFringe {
    def main(args:Array[String]) = {
        val t1 = Branch(Branch(Leaf(1),Leaf(2)),Leaf(3))
        val t2 = Branch(Leaf(1),Branch(Leaf(2),Leaf(3)))
        val t3 = Branch(Leaf(1),Branch(Leaf(2),Leaf(4)))
        println("t1:"); for (x &lt;- (new TreeFringe(t1))) println(x)
        println("t2:"); for (x &lt;- (new TreeFringe(t2))) println(x)
        println("t3:"); for (x &lt;- (new TreeFringe(t3))) println(x)
        println("sameFringe(t1,t2)="+sameFringe(t1,t2))
        println("sameFringe(t1,t3)="+sameFringe(t1,t3))
    }
    //include the sameFringe method in this object
}
</pre>

<a name="morepossibilities"/>
<h3>More Possibilities</h3>

Some other possible uses for generators or coroutines:

<ul>
<li>Pipelines: A sequence of tasks can operate on a stream of data,
    with each task reading data from an input queue and writing to an
    output queue which is the input queue of the next task in the sequence.
</li><li>Fan-out: A single producer with multiple consumers can be implemented
    by using a fan-out coroutine that reads from its input queue and writes
    the same data to multiple output queues, each of which is the input
    queue to one of the multiple consumers.
</li><li>Fan-in: Multiple producers can use a single shared output queue so that the
    coroutine using that queue as its input queue receives data from
    multiple sources.  If you stick with a single-thread scheduler,
    you don't have to worry about synchronization or other concurrent
    access issues on the shared queue.
    By combining Pipelines, Fan-out and Fan-in, we can create arbitrary
    networks of communicating coroutines.
</li><li>State machines: For any situation in which a task has to maintain state
    based on one or more inputs, a coroutine or generator can be used to
    allow some of that state to be stored as the location of current
    execution in the code, which often makes the code simpler to write
    and maintain.
</li><li>Parsers: A parser is a typical example of a producer that reads an
    input stream and maintains state. As the parser collects input characters
    (which could be provided by another coroutine in a pipeline)
    and resolves them into tokens, it writes them to its output queue
    where the tokens are available to the routine handling the next level of
    analysis.
</li></ul><div class="blogger-post-footer"><img alt="" height="1" src="https://blogger.googleusercontent.com/tracker/7045524330253482541-8294051801503348978?l=jim-mcbeath.blogspot.com" width="1"/></div></div>
    </content>
    <updated>2010-09-08T03:57:38Z</updated>
    <published>2010-09-08T03:53:00Z</published>
    <category scheme="http://www.blogger.com/atom/ns#" term="scala"/>
    <author>
      <name>Jim McBeath</name>
      <email>noreply@blogger.com</email>
      <uri>http://www.blogger.com/profile/10541190774989580614</uri>
    </author>
    <source>
      <id>tag:blogger.com,1999:blog-7045524330253482541</id>
      <author>
        <name>Jim McBeath</name>
        <email>noreply@blogger.com</email>
        <uri>http://www.blogger.com/profile/10541190774989580614</uri>
      </author>
      <link href="http://jim-mcbeath.blogspot.com/feeds/posts/default" rel="http://schemas.google.com/g/2005#feed" type="application/atom+xml"/>
      <link href="http://www.blogger.com/feeds/7045524330253482541/posts/default" rel="self" type="application/atom+xml"/>
      <link href="http://jim-mcbeath.blogspot.com/" rel="alternate" type="text/html"/>
      <link href="http://pubsubhubbub.appspot.com/" rel="hub" type="text/html"/>
      <link href="http://www.blogger.com/feeds/7045524330253482541/posts/default?start-index=26&amp;max-results=25" rel="next" type="application/atom+xml"/>
      <subtitle>Coding and Life</subtitle>
      <title>Jim McBeath</title>
      <updated>2010-09-08T12:58:45Z</updated>
    </source>
  </entry>

  <entry xml:lang="en">
    <id>http://www.scala-lang.org/7560 at http://www.scala-lang.org</id>
    <link href="http://www.scala-lang.org/node/7560" rel="alternate" type="text/html"/>
    <title>What's new in Scala 2.8 - Chained Package Clauses</title>
    <summary type="xhtml"><div xmlns="http://www.w3.org/1999/xhtml"><p>If you have already looked at some larger Scala 2.8 programs you might have been puzzled to see that source files now sometimes start with multiple chained package clauses, like this:</p> <p>  <strong>package org.myproject<br/>   package tests<br/>   ...</strong></p> <p>What does this mean? <a href="http://www.scala-lang.org/docu/files/package-clauses/packageclauses.html">Find out here.</a></p></div>
    </summary>
    <updated>2010-09-07T15:00:24Z</updated>
    <author>
      <name>odersky</name>
    </author>
    <source>
      <id>http://www.scala-lang.org/</id>
      <link href="http://www.scala-lang.org/" rel="alternate" type="text/html"/>
      <link href="http://www.scala-lang.org/rss.xml" rel="self" type="application/rss+xml"/>
      <title>The Scala Programming Language</title>
      <updated>2010-09-09T03:01:10Z</updated>
    </source>
  </entry>

  <entry>
    <id>tag:blogger.com,1999:blog-7045524330253482541.post-8501641801714740144</id>
    <link href="http://jim-mcbeath.blogspot.com/feeds/8501641801714740144/comments/default" rel="replies" type="application/atom+xml"/>
    <link href="https://www.blogger.com/comment.g?blogID=7045524330253482541&amp;postID=8501641801714740144" rel="replies" type="text/html"/>
    <link href="http://www.blogger.com/feeds/7045524330253482541/posts/default/8501641801714740144" rel="edit" type="application/atom+xml"/>
    <link href="http://www.blogger.com/feeds/7045524330253482541/posts/default/8501641801714740144" rel="self" type="application/atom+xml"/>
    <link href="http://jim-mcbeath.blogspot.com/2010/09/scala-coroutines.html" rel="alternate" type="text/html"/>
    <title>Scala Coroutines</title>
    <content type="xhtml"><div xmlns="http://www.w3.org/1999/xhtml">An implementation of coroutines on top of
Scala's delimited continuations.

<br/><br/>
In my
<a href="http://jim-mcbeath.blogspot.com/2010/08/delimited-continuations.html">
previous post</a>
I said that delimited continuations could be used to create
interesting control constructs.
In this post I give examples of one such construct: coroutines.

<br/><br/>
I describe the implementation of a library to make it easier to
write coroutines, and I give an example that is built on that library.
If you want to go straight to the example, see the section
<a href="http://jim-mcbeath.blogspot.com/feeds/posts/default#producer-consumer">Producer-Consumer</a>.

<br/><br/>
Like my previous post on
<a href="http://jim-mcbeath.blogspot.com/2010/08/delimited-continuations.html">
delimited continuations</a>,
this is a long post.
However, though long, it should be much easier going than that post.
You don't need to read and understand that post in order to understand
this post, but it will help in two places:
<ol>
<li>In the discussion of the
<a href="http://jim-mcbeath.blogspot.com/feeds/posts/default#coscheduler-api">CoScheduler API</a> and
<a href="http://jim-mcbeath.blogspot.com/feeds/posts/default#coscheduler-impl">implementation</a>,
an understanding of <code>reset</code> and <code>shift</code> is required.
</li><li>You need to understand at some level about CPS code and its
<a href="http://jim-mcbeath.blogspot.com/2010/08/delimited-continuations.html#control_construct_restrictions">restrictions</a>
when writing coroutines or using the CPS-only methods in
<code>CoQueue</code> and <code>Blocker</code>.
</li></ol>

<h3>Contents</h3>

<ul>
<li><a href="http://jim-mcbeath.blogspot.com/feeds/posts/default#coroutines">Coroutines</a>
</li><li><a href="http://jim-mcbeath.blogspot.com/feeds/posts/default#why-coroutines">Why Use Coroutines</a>
</li><li><a href="http://jim-mcbeath.blogspot.com/feeds/posts/default#library">Building a Coroutine Library</a>
</li><li><a href="http://jim-mcbeath.blogspot.com/feeds/posts/default#blocker">Blocker</a>
</li><li><a href="http://jim-mcbeath.blogspot.com/feeds/posts/default#coqueue">CoQueue</a>
</li><li><a href="http://jim-mcbeath.blogspot.com/feeds/posts/default#attempt-to-avoid-blocking">An Attempt to Avoid Blocking</a>
</li><li><a href="http://jim-mcbeath.blogspot.com/feeds/posts/default#coscheduler-api">CoScheduler API</a>
</li><li><a href="http://jim-mcbeath.blogspot.com/feeds/posts/default#coscheduler-impl">CoScheduler Implementation</a>
</li><li><a href="http://jim-mcbeath.blogspot.com/feeds/posts/default#defaultcoscheduler">DefaultCoScheduler</a>
</li><li><a href="http://jim-mcbeath.blogspot.com/feeds/posts/default#other-schedulers">Other Schedulers</a>
</li><li><a href="http://jim-mcbeath.blogspot.com/feeds/posts/default#producer-consumer">Producer-Consumer</a>
</li><li><a href="http://jim-mcbeath.blogspot.com/feeds/posts/default#resources">Resources</a>
</li></ul>

<a name="coroutines"/>
<h3>Coroutines</h3>

The <a href="http://en.wikipedia.org/wiki/Coroutine">
Wikipdeia coroutines</a> page
says coroutines are a generalization of subroutines:
whereas a subroutine starts at the beginning every time it is called,
a coroutine starts at the beginning the first time it is called,
but can start at any other point on successive calls.
Generally this means that on successive calls, it continues running
from the point where it most recently returned.

<br/><br/>
Instead of using a <code>return</code> statement,
coroutines typically use a <code>yield</code> statement.
A <code>yield</code> statement
indicates that the routine is done executing for now,
and will resume execution following the <code>yield</code> statement
the next time it is called.

<br/><br/>
In the classic definition of coroutines,
the <code>yield</code> statement indicates which coroutine is to be run next.
With two coroutines, each always yields to the other;
with more than two, a coroutine might have code to determine which
other coroutine to yield to.

<br/><br/>
Unfortunately for coroutines, <code>yield</code>
is already a keyword in Scala, so we can't use it for our purposes.
We can either pick a slightly different word such as
<code>yld</code> or <code>yieldTo</code>,
or we can just use a different term altogether.

<br/><br/>
The classic example of the use of coroutines is a pair of routines,
one of which (the producer) generates data and
one of which (the consumer) consumes data.
These two routines are connected by a queue; the producer puts data
into the queue and the consumer takes data out of the queue.

<br/><br/>
This same producer-consumer pair is also a typical example
of multi-thread code.
Ted Neward uses this producer-consumer example in his
<a href="http://www.ibm.com/developerworks/java/library/j-scala02049.html">
blog post</a> describing the concurrency benefits of using Scala.

<br/><br/>
In the multi-thread producer-consumer example,
the producer thread runs and places data into the queue
until the queue is full,
at which point that thread stops running until the queue empties out enough
for it to add more data.
Meanwhile the consumer thread runs and takes data out of the queue
until the queue is empty,
at which point that thread stop running until the queue contains more data.
If the host on which the multi-thread application is running contains
more than one processor, both of these threads might be running
at the same time.

<br/><br/>
I like to think of coroutines as being like multi-thread code,
only without multiple threads.
The coroutine version of the producer-consumer example
works essentially the same as the multi-thread version,
except that only one of the two is ever running at one point in time.
The producer runs and places data into the queue until it is full,
at which point it pauses and the consumer starts running.
The consumer takes data out of the queue until it is empty,
at which point it pauses and the producer starts running again.
<br/><br/>
In both the multi-thread and the coroutine version of this example,
there is some state that is saved while each routine is paused
waiting for the queue to fill or empty.
In the multi-thread example, that state is saved in the thread.
In our coroutine example, we use a different mechanism to save
that state: a delimited continuation.

<a name="why-coroutines"/>
<h3>Why Use Coroutines</h3>

If coroutines are like multi-thread code, why use them and have to
deal with continuations rather than just using threads?
Here are some possible reasons:
<ul>
<li>With the
    <a href="http://jim-mcbeath.blogspot.com/feeds/posts/default#defaultcoscheduler">default scheduler</a>
    that runs everything in one thread,
    you don't need to worry about concurrency issues such as
    multiple concurrent access to shared state.
</li><li>You can create your own scheduler to control when to run each of your
    coroutines.  If you want that scheduler to use a thread pool and
    run coroutines concurrently, you can do that (assuming you then
    deal with concurrency issues in your coroutines).
</li><li>An application can handle more suspended continuations than it can
    suspended threads (for example, see slide 19 of Phillip Haller's
    <a href="http://lamp.epfl.ch/~phaller/doc/ScalaActors.pdf">presentation</a>
    on Actors, where he says an app can handle up to 5,000
    threads, but up to 1,200,000 actors).
</li></ul>

<a name="library"/>
<h3>Building a Coroutine Library</h3>

It is <a href="http://scala-programming-language.1934581.n4.nabble.com/Delimited-continuations-and-Scala-td1947779.html">
possible</a> to write coroutines directly in Scala code using
<code>reset</code> and <code>shift</code>, but
dealing with delimited continuations can be tricky,
so I wanted to isolate all of that code into a reusable library
that would make it easier to write coroutines
as well as allow encapsulating more sophisticated
capabilities within the library.
The package name I selected for this library is
<code>net.jimmc.scoroutine</code>.
The source code is
<a href="http://github.com/jimmc/scoroutine">
available</a> on github.

<br/><br/>
I started with a change that makes these coroutines look less like
coroutines and more like the multi-thread model:
rather than have a coroutine specify what other coroutine is to be run,
I wanted to be able to specify only that the coroutine is ready to give
up control.
Essentially, rather than yielding to another coroutine,
I always yield to a scheduler,
and the scheduler selects and then yields to the next coroutine.
Given such a scheduler (described <a href="http://jim-mcbeath.blogspot.com/feeds/posts/default#coscheduler-api">below</a>),
we can create a few simple constructs on which to build our
coroutine API.

<a name="blocker"/>
<h3>Blocker</h3>

In the typical producer-consumer example,
there is an explicit check to see if the routine is blocked,
and if so, then a call to <code>yield</code> is made.
I wanted something more generic, so I created an abstract trait
<a href="http://github.com/jimmc/scoroutine/tree/master/src/main/scala/net/jimmc/scoroutine/Blocker.scala"><code>Blocker</code></a>
to represent the condition that a routine could be blocked by something:

<br/><br/>
<input id="hlButton" type="submit" value="Highlight Syntax"/>
<pre class="scala" name="hlcode">package net.jimmc.scoroutine

trait Blocker {
    def isBlocked: Boolean
}
</pre>

The implementations of this for the producer and consumer are straightforward:
for the producer, <code>isBlocked</code> returns true when the
queue is full;
for the consumer, <code>isBlocked</code> returns true when
the queue is empty.

<br/><br/>
Given the <code>isBlocked</code> method, the typical coroutine always
includes a code fragment that looks something like this:

<pre class="scala" name="hlcode">while (isBlocked)
    yield control
</pre>

Since we will always be yielding control to the scheduler, we can encapsulate
this into a more convenient method, which I have called
<code>waitUntilNotBlocked</code>.
I added this function to my <code>Blocker</code> trait, and delegated it to
a scheduler of type
<a href="http://github.com/jimmc/scoroutine/tree/master/src/main/scala/net/jimmc/scoroutine/CoScheduler.scala"><code>CoScheduler</code></a>:

<pre class="scala" name="hlcode">package net.jimmc.scoroutine

trait Blocker {
    val scheduler: CoScheduler  //class must override to provide instance
    def isBlocked: Boolean

    def waitUntilNotBlocked:Unit = {
        scheduler.waitUntilNotBlocked(this)
    }
}
</pre>

We pass <code>this</code> to the scheduler so that it can call our
<code>isBlocked</code> method and continue our execution only
when <code>isBlocked</code> returns false.

<br/><br/>
There is one more detail to be added to <code>Blocker</code>,
but it is an important one.
I stated above that this implementation is built on
top of delimited continuations.
When we call <code>waitUntilNotBlocked</code>
and we are blocked, we want the coroutine library to wait until we
are no longer blocked and then continue execution of our routine.
The coroutine library will be using delimited continuations to do this,
and since our routine might be suspended, the signature
for the <code>waitUntilNotBlocked</code> method must
include the
<a href="http://jim-mcbeath.blogspot.com/2010/08/delimited-continuations.html#annotations">
<code>suspendable</code></a> annotation.
We add that annotation along with a suitable <code>import</code> statement
to get our final version of <code>Blocker</code>:

<pre class="scala" name="hlcode">package net.jimmc.scoroutine

import scala.util.continuations._

trait Blocker {
    val scheduler: CoScheduler  //class must override to provide instance
    def isBlocked: Boolean

    def waitUntilNotBlocked:Unit @suspendable = {
        scheduler.waitUntilNotBlocked(this)
    }
}
</pre>

<a name="coqueue"/>
<h3>CoQueue</h3>

Once we have <code>Blocker</code>, it is easy to compose a blocking
version of the standard
<a href="http://www.scala-lang.org/api/current/scala/collection/mutable/Queue.html"><code>Queue</code></a> class
(where by "blocking" I mean that the coroutine will be suspended until
the specified <code>Blocker</code> is no longer blocked).
We want a version of the
<a href="http://www.scala-lang.org/api/current/scala/collection/mutable/Queue.html#enqueue(A*):Unit">
<code>Queue.enqueue</code></a> function
that blocks when the queue is full,
and a version of the
<a href="http://www.scala-lang.org/api/current/scala/collection/mutable/Queue.html#dequeue():A">
<code>Queue.dequeue</code></a> function
that blocks when the queue is empty.
We create a thin wrapper around the <code>Queue</code> class,
which we call <code>CoQueue</code>,
to implement our blocking methods for use with our coroutines.
For each of our two blocking conditions,
we create an instance of <code>Blocker</code>
with those conditions as each of their <code>isBlocked</code> functions,
and we use those <code>Blocker</code> instances to create our
<code>blockingEnqueue</code> and <code>blockingDequeue</code> methods.

<br/><br/>
Because the <code>blockingEnqueue</code>
and <code>blockingDequeue</code> methods might block,
they must be annotated as <code>suspendable</code>,
which means they can only be called from within CPS code.
Here is our entire
<a href="http://github.com/jimmc/scoroutine/tree/master/src/main/scala/net/jimmc/scoroutine/CoQueue.scala"><code>CoQueue</code></a>
class:

<pre class="scala" name="hlcode">package net.jimmc.scoroutine

import scala.util.continuations._
import scala.collection.mutable.Queue

class CoQueue[A](val scheduler:CoScheduler, val waitSize:Int)
        extends Queue[A] { coqueue =&gt;

    val enqueueBlocker = new Blocker() {
        val scheduler = coqueue.scheduler
        def isBlocked() = length &gt;= waitSize
    }

    val dequeueBlocker = new Blocker() {
        val scheduler = coqueue.scheduler
        def isBlocked() = isEmpty
    }

    def blockingEnqueue(x:A):Unit @suspendable = {
        enqueueBlocker.waitUntilNotBlocked
        enqueue(x)
    }

    def blockingDequeue():A @suspendable = {
        dequeueBlocker.waitUntilNotBlocked
        dequeue
    }
}
</pre>

<a name="attempt-to-avoid-blocking"/>
<h3>An Attempt to Avoid Blocking</h3>

You might wonder if we could implement <code>blockingEnqueue</code>
as follows so as to avoid the call to the scheduler's
<code>waitUntilNotBlocked</code> method:

<pre class="scala" name="hlcode">//this won't compile
    def blockingEnqueue(x:A):Unit @suspendable = {
        if (enqueueBlocker.isBlocked)
            enqueueBlocker.waitUntilNotBlocked
        enqueue(x)
    }
</pre>

However, the compiler gives this error message:

<pre class="scala" name="hlcode">CoQueue.scala:22: error: type mismatch;
 found   : Unit
 required: Unit @scala.util.continuations.cpsParam[Unit,Unit]
        if (enqueueBlocker.isBlocked)
        ^
</pre>

Syntactically, the problem is that the above one-sided
<code>if</code> statement is equivalent to

<pre class="scala" name="hlcode">        if (enqueueBlocker.isBlocked)
            enqueueBlocker.waitUntilNotBlocked
        else
            ()
</pre>

The type of <code>()</code> is <code>Unit</code>, but the type of
<code>waitUntilNotBlocked</code> is <code>Unit @suspendable</code>,
so there is a type mismatch.

<br/><br/>
You might think we could use some trickery such as this:

<pre class="scala" name="hlcode">//compiles, but won't run properly
    def unitSuspendable:Unit @suspendable = ()

    def blockingEnqueue(x:A):Unit @suspendable = {
        if (enqueueBlocker.isBlocked)
            enqueueBlocker.waitUntilNotBlocked
        else
            unitSuspendable
        enqueue(x)
    }
</pre>

This will compile without errors, but will not work properly.
The problem is that we are trying to define one code path that
is CPS (through <code>waitUntilNotBlocked</code>) and one path that
is not (through <code>unitSuspendable</code>).
The CPS compiler plugin transforms the code to use continuations,
which, as you might recall from the discussion in my previous post,
packages the rest of the function up in a continuation and passes it
along to the called function.
But the <code>unitSuspendable</code> expression does nothing with that
continuation; it neither executes it nor saves it for later execution.
Thus as soon as this code path is taken, the continuation -
which represents
the remainder of the execution of the entire delimited continuation,
including the caller of this function -
is dropped, and the whole delimited continuation is done.

<a name="coscheduler-api"/>
<h3>CoScheduler API</h3>

The scheduler is the piece of the coroutine library that saves the
continuations for all of the participating coroutines and determines
when to execute those continuations.
By design, all of the tricky stuff is encapsulated in this class.
I have divided the discussion of the scheduler into two section:
this first section discusses at a high level the tasks for which the
schedule must take responsibility, and defines an API to perform
those tasks.
The following section describes the implementation of that API.
If you don't want to get too far into the delimited continuation stuff,
you can read just this section and skip the implementation section.

<br/><br/>
I started with the requirements that it should be possible to
write a scheduler that:
<ol>
<li>uses one thread for all participating coroutines, or uses
    a thread pool so that multiple coroutines can run at once;
</li><li>uses a simple algorithm
    to select which coroutine to run next, such as round-robin,
    or a more complex algorithm, such as a priority-based approach;
</li><li>can be instantiated multiple times
    so that different collections of coroutines can be managed with
    different schedulers.
</li></ol>

In order to allow all of the above,
the scheduler API is defined in a trait,
which I call <code>CoScheduler</code>.
<code>CoScheduler</code> needs to define three basic functions:
<ol>
<li>Register a coroutine.
    I chose to do this with a method that accepts a block of code which
    is the coroutine body.
    Since the coroutine body might be suspended, the signature for that
    argument must include the <code>suspendable</code> annotation.
    I call this method <code>addRoutine</code>.
    To improve tracing, I also pass in a name argument that can be
    used to identify that coroutine.
</li><li>Wait until a coroutine is no longer blocked.
    This is the method to which <code>Blocker.waitUntilNotBlocked</code>
    will delegate.
    It is also called <code>waitUntilNotBlocked</code>, and takes an
    argument which is the <code>Blocker</code> whose
    <code>isBlocked</code> method will be used to make that determination.
    Since this method will be called from the coroutine body or a method
    called from that body, it must be marked as <code>suspendable</code>.
</li><li>Run a coroutine.
    There are two flavors of this: run a single step, returning as soon as
    one coroutine has run and has returned control to the scheduler,
    or run as many steps as possible,
    until there are no more unblocked coroutines to run.
    I call these two methods
    <code>runNextUnblockedRoutine</code> and <code>runUntilBlockedOrDone</code>,
    respectively.
    Since these methods are meant to be called from the main application,
    not from within a coroutine, they are not marked as
    <code>suspendable</code>.
    <br/><br/>
    When one of the <code>run</code> methods returns,
    we would like to know whether
    there are some blocked coroutines,
    all of our coroutines have completed,
    or we don't know which because we only ran one routine.
    In order to return this indication, we define a sealed class
    <code>RunStatus</code> with three case objects representing
    these three possibilities.
</li></ol>

The API of our
<a href="http://github.com/jimmc/scoroutine/tree/master/src/main/scala/net/jimmc/scoroutine/CoScheduler.scala"><code>CoScheduler</code></a>
trait thus looks like this:

<pre class="scala" name="hlcode">package net.jimmc.scoroutine

sealed abstract class RunStatus
case object RanOneRoutine extends RunStatus
case object SomeRoutinesBlocked extends RunStatus
case object AllRoutinesDone extends RunStatus

trait CoScheduler {
    def addRoutine(name:String)(body: =&gt; Unit @suspendable)

    def waitUntilNotBlocked(b:Blocker):Unit @suspendable

    def runNextUnblockedRoutine():RunStatus
    def runUntilBlockedOrDone():RunStatus
}
</pre>

If you are interested in using the <code>scoroutine</code> library
to write coroutines, but you don't care how it works internally,
then you can skip the next few sections and pick up again at
<a href="http://jim-mcbeath.blogspot.com/feeds/posts/default#producer-consumer">Producer-Consumer</a>.

<a name="coscheduler-impl"/>
<h3>CoScheduler Implementation</h3>

The reason for implementing <code>CoScheduler</code> as a trait rather
than a class is to make it easier to create multiple implementations.
On the other hand, there is some functionality which is likely to be
the same in all implementations, and since Scala allows us to include
code in traits, we will add the implementation of those methods to the trait.

<br/><br/>
For example, given the <code>runNextUnblockedRoutine</code> method,
the <code>runUntilBlockedOrDone</code> method is a simple loop that
calls <code>runNextUnblockedRoutine</code> until it does not run something.

<br/><br/>
Likewise, if we internally create an instance of a <code>Blocker</code>
in <code>addRoutine</code>,
we can implement both that method and <code>waitUntilNotBlocked</code>
on top of a single method that stores a continuation,
which we will call <code>setRoutineContinuation</code>.

<br/><br/>
This means we can create a concrete scheduler class that extends the
<code>CoScheduler</code> trait by implementing just two functions:
<code>runNextUnblockedRoutine</code> and
<code>setRoutineContinuation</code>.

<br/><br/>
Below is what our implementation of <code>CoScheduler</code> looks like
after making the above changes.

<pre class="scala" name="hlcode">package net.jimmc.scoroutine

import scala.util.continuations._

sealed class RunStatus
case object RanOneRoutine extends RunStatus
case object SomeRoutinesBlocked extends RunStatus
case object AllRoutinesDone extends RunStatus

trait CoScheduler { cosched =&gt;
    private[scoroutine] def setRoutineContinuation(
            b:Blocker, cont:Option[Unit=&gt;Unit]):Unit
    def runNextUnblockedRoutine():RunStatus

    /* We use a class rather than an object because we are using the
     * instance as a key to find more info about the associated routine. */
    class BlockerNever() extends Blocker {
        val scheduler = cosched
        val isBlocked = false
    }

    def addRoutine(name:String)(body: =&gt; Unit @suspendable) {
        reset {
            val blocker = new BlockerNever()
            waitUntilNotBlocked(blocker)
            body
        }
    }

    def runUntilBlockedOrDone():RunStatus = {
        var status:RunStatus = RanOneRoutine
        while (status==RanOneRoutine) {
            status = runNextUnblockedRoutine()
        }
        status
    }

    def waitUntilNotBlocked(b:Blocker):Unit @suspendable = {
        shift( (cont: Unit=&gt;Unit) =&gt; {
            setRoutineContinuation(b,Some(cont))
        })
    }
}
</pre>

As we already knew based on the existence of the
<code>suspendable</code> annotation, there are two methods that deal
with CPS code: <code>addRoutine</code> and <code>waitUntilNotBlocked</code>.

<br/><br/>
Before examining these functions, it is worth reviewing one point about
how <code>reset</code> and <code>shift</code> work.
When there is a <code>shift</code> call within a <code>reset</code> block,
the CPS compiler plugin transforms the code within the <code>reset</code>
block such that the code after the <code>shift</code> block is passed
as a continuation argument to the <code>shift</code> block.
The code within the <code>shift</code> block is thus the last code
to be executed within the <code>reset</code> block.
The code that is within the <code>reset</code> but outside of the
<code>shift</code> is CPS code, but the code within the <code>shift</code>
block is not CPS code.
In other words, once within a <code>reset</code> block, we are executing
CPS code until we get into the <code>shift</code> block, at which point
we are no longer executing CPS code.
The continuation contains CPS code; if we call the continuation from
within our <code>shift</code> code, we transition from non-CPS code
into CPS code.
But if we happen to save the continuation,
we can directly execute it later from any non-CPS code, and that will likewise
transition us into the CPS code of the continuation.

<br/><br/>
The <code>waitUntilNotBlocked</code> function takes as an argument the
<code>Blocker</code> that will tell us when the calling coroutine is
allowed to run again, and, along with the continuation passed in to
the <code>shift</code>, passes it to
<code>setRoutineContinuation</code>.
That function saves the continuation and its associated <code>Blocker</code>
and returns without executing the continuation.
Because we are returning without executing the continuation,
control returns to the first statement past the end of the
enclosing <code>reset</code> block,
or, if the current code/continuation (i.e. the CPS code containing the call to
<code>waitUntilNotBlocked</code>) was directly executed from non-CPS code,
to the statement after
the point at which that continuation was executed.

<br/><br/>
The <code>addRoutine</code> function creates a <code>Blocker</code> that
never blocks, then calls <code>waitUntilNotBlocked</code> with that
blocker.  Since <code>waitUntilNotBlocked</code> is a CPS function
(marked with the <code>suspendable</code> annotation),
the remainder of the code in the <code>reset</code> block is turned
into a continuation and passed along to <code>waitUntilNotBlocked</code>.
When that method calls <code>shift</code>, the continuation we passed to
<code>waitUntilNotBlocked</code> - i.e. our call to <code>body</code> -
is part of the continuation passed to the <code>shift</code>.
Thus when that method saves the continuation, that saved continuation
includes the call to the coroutine body.
Since the continuation is not immediately executed, control returns
to the end of the <code>reset</code> block, and we return from
<code>addRoutine</code> with our coroutine sitting in the scheduler
ready to start running.

<a name="defaultcoscheduler"/>
<h3>DefaultCoScheduler</h3>

Given the <code>CoScheduler</code> trait described above, the only
functionality that remains for our concrete class is
to implement a mechanism for storing continuations
and selecting the next one to run.
The
<a href="http://github.com/jimmc/scoroutine/tree/master/src/main/scala/net/jimmc/scoroutine/DefaultCoScheduler.scala"><code>DefaultCoScheduler</code></a>
implements a simple round-robin
scheduling mechanism, selecting the next runnable continuation each
time it is invoked.
Note that this implementation has been designed to be simple, but
is not very efficient.
In particular, it will not exhibit good performance when there are a large
number of coroutines of which only a few are runnable at any time.

<br/><br/>
We define a case class <code>BlockerInfo</code> to tie together a
<code>Blocker</code> and its associated continuation,
an <code>ArrayBuffer</code> to store an ordered set of those,
and a map to find one given a <code>Blocker</code>.

<br/><br/>
The <code>setRoutineContinuation</code> function adds a new
<code>BlockerInfo</code> to our array if we don't already have one
for the given <code>Blocker</code>, or updates the existing one if we do.

<br/><br/>
The <code>runNextUnblockedRoutine</code> function does a simple
linear scan through the array of items, starting just past where we left off
the last time, looking for the first unblocked continuation and
running it.
If there were no runnable continuations, we return a status code
without running anything.

<pre class="scala" name="hlcode">package net.jimmc.scoroutine

import scala.collection.mutable.ArrayBuffer
import scala.collection.mutable.HashMap

class DefaultCoScheduler extends CoScheduler {
    val blockerIndexMap = new HashMap[Blocker,Int]
    case class BlockerInfo(val blocker:Blocker, index:Int,
            var cont:Option[Unit=&gt;Unit])
    val blockerList = new ArrayBuffer[BlockerInfo]
    var nextIndex = 0

    private[scoroutine] def setRoutineContinuation(
            b:Blocker,cont:Option[Unit=&gt;Unit]) {
        if (blockerIndexMap.get(b).isEmpty) {
            val nextIndex = blockerIndexMap.size
            blockerIndexMap.put(b,nextIndex)
            blockerList += BlockerInfo(b, nextIndex, cont)
        } else {
            val n = blockerIndexMap(b)
            blockerList(n).cont = cont
        }
    }

    def runNextUnblockedRoutine():RunStatus = {
        var blockedCount = 0
        for (i &lt;- 0 until blockerList.size) {
            val index = (nextIndex + i) % blockerList.size
            val bInfo = blockerList(index)
            if (bInfo.cont.isDefined &amp;&amp; bInfo.blocker.isBlocked) {
                blockedCount += 1
            }
            if (bInfo.cont.isDefined &amp;&amp; !bInfo.blocker.isBlocked) {
                nextIndex = index + 1
                val nextCont = bInfo.cont
                bInfo.cont = None
                nextCont.get()          //run the continuation
                return RanOneRoutine
            }
        }
        if (blockedCount &gt; 0) {
            SomeRoutinesBlocked
        } else {
            AllRoutinesDone
        }
    }
}
</pre>

Note that <code>DefaultCoScheduler</code> does not import
the continuations package.
It does not use <code>reset</code>, <code>shift</code>,
or any of the CPS annotations such as <code>suspendable</code>.
This is because none of this code is CPS code.
<code>runNextUnblockedRoutine</code> is called from non-CPS code,
and although <code>setRoutineContinuation</code> is called from
CPS code, it does not itself call any CPS functions nor does it use
<code>shift</code>, so it does not need to be declared as CPS code.

<a name="other-schedulers"/>
<h3>Other Schedulers</h3>

<code>DefaultCoScheduler</code> implements a basic scheduling algorithm.
It is intended for use with small numbers of coroutines and has not
been optimized.
Other schedulers could be written that are optimized for other
situations, such as large numbers of coroutines,
coroutines with different priorities,
or "stickiness" so that a running coroutine continues to run
until it is blocked before the next coroutine runs.
Since the code that creates the coroutines starts by creating
the scheduler that controls those coroutines,
it would be simple to create a scheduler other than
<code>DefaultCoScheduler</code> for use with a particular
set of coroutines.

<a name="producer-consumer"/>
<h3>Producer-Consumer</h3>

Let's see how the Producer-Consumer example
(<a href="http://github.com/jimmc/scoroutine/tree/master/src/example/scala/ProdConTest.scala"><code>ProdConTest</code></a>)
looks using the
<code>scoroutine</code> library:

<pre class="scala" name="hlcode">import scala.util.continuations._

import net.jimmc.scoroutine.DefaultCoScheduler
import net.jimmc.scoroutine.CoQueue

object ProdConTest {
    def main(args:Array[String]) = {
        val prodcon = new ProduceAndConsume()
        prodcon.run
    }
}

class ProdCon() {
    val sched = new DefaultCoScheduler
    val buf = new CoQueue[Int](sched,2)

    def run() {
        sched.addRoutine("producer"){
            var i = 0
            while (i &lt; 4) {
                buf.blockingEnqueue(i)
            }
        }
        sched.addRoutine("consumer"){
            val total = buf.blockingDequeue +
                    buf.blockingDequeue + buf.blockingDequeue
            println("consume total is "+total)
        }
        sched.runUntilBlockedOrDone
    }
}
</pre>

After the imports and a simple <code>main</code> method
for testing, we have the <code>ProdCon</code> class with the
actual producer-consumer definition.

<br/><br/>
We start by setting up two objects:
the scheduler that will control our two coroutines,
and a queue for communication between them.
We then register two coroutines with our scheduler,
one for the producer and one for the consumer, and we
call <code>sched.runUntilBlockedOrDone</code>
to run the coroutines until
there is nothing runnable left on that scheduler.

<br/><br/>
You can't tell in this example, but the code blocks being passed
to <code>addRoutine</code> are CPS code, the same as the body of
a <code>reset</code> block.
If you decide to refactor this code and push the
<code>blockingEnqueue</code> or <code>blockingDequeue</code> calls down into a
subroutine, that subroutine will have to be marked with the
<code>suspendable</code> annotation.
Also, because coroutine bodies are CPS code, there are
there are some <a href="http://jim-mcbeath.blogspot.com/2010/08/delimited-continuations.html#control_construct_restrictions">restrictions</a>
on what control constructs can be used.
You can see what this looks like in the
<a href="http://github.com/jimmc/scoroutine/tree/master/src/example/scala/ProdConTestWithSubs.scala">
<code>ProdConTestWithSubs</code></a> source code in the
<a href="http://github.com/jimmc/scoroutine/tree/master/src/example/scala">
scoroutine examples</a>.

<br/><br/>
I will give some more examples in my next post,
a followup about Generators.

<a name="resources"/>
<h3>Resources</h3>

<ul>
<li>My original blog post on
    <a href="http://jim-mcbeath.blogspot.com/2010/08/delimited-continuations.html">
    Delimited Continuations</a>,
    which includes its own
    <a href="http://jim-mcbeath.blogspot.com/2010/08/delimited-continuations.html#resources">
    Resources</a> section.
</li><li>The <a href="http://github.com/jimmc/scoroutine">net.jimmc.scoroutine</a> library on github.
</li><li><a href="http://code.google.com/p/python-multitask/">python-multitask</a>,
    a similar framework for Python.
</li></ul><div class="blogger-post-footer"><img alt="" height="1" src="https://blogger.googleusercontent.com/tracker/7045524330253482541-8501641801714740144?l=jim-mcbeath.blogspot.com" width="1"/></div></div>
    </content>
    <updated>2010-09-06T21:38:08Z</updated>
    <published>2010-09-06T21:38:00Z</published>
    <category scheme="http://www.blogger.com/atom/ns#" term="scala"/>
    <author>
      <name>Jim McBeath</name>
      <email>noreply@blogger.com</email>
      <uri>http://www.blogger.com/profile/10541190774989580614</uri>
    </author>
    <source>
      <id>tag:blogger.com,1999:blog-7045524330253482541</id>
      <author>
        <name>Jim McBeath</name>
        <email>noreply@blogger.com</email>
        <uri>http://www.blogger.com/profile/10541190774989580614</uri>
      </author>
      <link href="http://jim-mcbeath.blogspot.com/feeds/posts/default" rel="http://schemas.google.com/g/2005#feed" type="application/atom+xml"/>
      <link href="http://www.blogger.com/feeds/7045524330253482541/posts/default" rel="self" type="application/atom+xml"/>
      <link href="http://jim-mcbeath.blogspot.com/" rel="alternate" type="text/html"/>
      <link href="http://pubsubhubbub.appspot.com/" rel="hub" type="text/html"/>
      <link href="http://www.blogger.com/feeds/7045524330253482541/posts/default?start-index=26&amp;max-results=25" rel="next" type="application/atom+xml"/>
      <subtitle>Coding and Life</subtitle>
      <title>Jim McBeath</title>
      <updated>2010-09-08T12:58:45Z</updated>
    </source>
  </entry>

  <entry>
    <id>tag:blogger.com,1999:blog-137400338062194307.post-6219257045879429481</id>
    <link href="http://feedproxy.google.com/~r/lalitpant/~3/v-evwmRbYtY/announcing-kojo-learning-environment.html" rel="alternate" type="text/html"/>
    <title>Announcing - The Kojo Learning Environment</title>
    <summary>Time seems to be flying by. It's been almost two years since my last post! I need to make sure that I write (much) more frequently going forward.I have been busy for the past many months working on a educational tool: The Kojo Learning Environment. It's finally time to announce it on my Blog!Kojo is (hopefully) a fun and friendly graphical environment for playing with:Beginner level Computer</summary>
    <content>&lt;img src="http://feeds.feedburner.com/~r/lalitpant/~4/v-evwmRbYtY" height="1" width="1"/&gt;</content>
    <updated>2010-09-06T04:24:00Z</updated>
    <category scheme="http://www.blogger.com/atom/ns#" term="kojo"/>
    <category scheme="http://www.blogger.com/atom/ns#" term="web development"/>
    <category scheme="http://www.blogger.com/atom/ns#" term="learning to program"/>
    <category scheme="http://www.blogger.com/atom/ns#" term="education"/>
    <category scheme="http://www.blogger.com/atom/ns#" term="scala"/><feedburner:origLink xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0">http://lalitpant.blogspot.com/2010/09/announcing-kojo-learning-environment.html</feedburner:origLink>
    <author>
      <name>Lalit Pant</name>
      <email>noreply@blogger.com</email>
    </author>
    <source>
      <id>tag:blogger.com,1999:blog-137400338062194307</id>
      <author>
        <name>Lalit Pant</name>
        <email>noreply@blogger.com</email>
      </author>
      <link href="http://lalitpant.blogspot.com/" rel="alternate" type="text/html"/>
      <link href="http://feeds.feedburner.com/lalitpant" rel="self" type="application/atom+xml"/>
      <link href="http://pubsubhubbub.appspot.com/" rel="hub" type="text/html"/>
      <subtitle>Lalit's technical blog; thoughts and ideas on the structure and flow of computer programs, and related matters.</subtitle>
      <title>All Things Runnable</title>
      <updated>2010-09-06T06:20:20Z</updated>
    </source>
  </entry>

  <entry>
    <id>tag:blogger.com,1999:blog-5448311202414367852.post-47879081272024491</id>
    <link href="http://blog.yuvimasory.com/feeds/47879081272024491/comments/default" rel="replies" type="application/atom+xml"/>
    <link href="http://blog.yuvimasory.com/2010/09/creating-standalone-executable-jar-with.html#comment-form" rel="replies" type="text/html"/>
    <link href="http://www.blogger.com/feeds/5448311202414367852/posts/default/47879081272024491" rel="edit" type="application/atom+xml"/>
    <link href="http://www.blogger.com/feeds/5448311202414367852/posts/default/47879081272024491" rel="self" type="application/atom+xml"/>
    <link href="http://blog.yuvimasory.com/2010/09/creating-standalone-executable-jar-with.html" rel="alternate" type="text/html"/>
    <title>Creating a standalone executable jar with Scala and SBT</title>
    <content type="xhtml"><div xmlns="http://www.w3.org/1999/xhtml">Executable jars (you know, the kind you run <tt>java -jar</tt> on) are a great way to distribute a compiled program. With Scala it's a little more complicated since the Scala library must be included. And with SBT it's more complicated yet.<br/><br/>Fortunately there's the <a href="http://github.com/nuttycom/sbt-proguard-plugin">sbt-proguard-plugin</a> to simplify the task. Proguard is normally used to remove unused code from a project to minimize the size of the resulting jar. But as a side effect it does create a functioning executable jar.<br/><br/>There's <i>very</i> little documentation out there for the plugin, so here's how I got it working.<br/><br/>Step 1) Edit your Project.scala (normally <tt>project/build/Project.scala</tt>).<br/>&lt;script src="http://gist.github.com/566283.js?file=gistfile1.scala"&gt;&lt;/script&gt;<br/><p><a href="http://gist.github.com/566283" target="_blank" title="Can't see the code?">Can’t see the code? </a></p><br/><br/>Step 2) Edit your Plugins.scala (you may need to create it as <tt>plugins/Plugins.scala</tt>).<br/>&lt;script src="http://gist.github.com/566281.js?file=gistfile1.scala"&gt;&lt;/script&gt;<br/><p><a href="http://gist.github.com/566281" target="_blank" title="Can't see the code?">Can’t see the code? </a></p><br/><br/>Step 3) Create the jar!<br/>Fire up SBT by running <tt>sbt</tt>, then do:<br/><tt>reload</tt><br/><tt>update</tt><br/><tt>proguard</tt><br/><br/>That should produce an executable jar <tt>target/scala_X.X.X/my-project-X.X.min.jar</tt>. Make sure you use the jar with <i>min</i> in its name.<br/><br/>You should now be able the run <tt>java -jar my-project-X.X.min.jar</tt> on any system with Java installed.<div class="blogger-post-footer"><img alt="" height="1" src="https://blogger.googleusercontent.com/tracker/5448311202414367852-47879081272024491?l=blog.yuvimasory.com" width="1"/></div></div>
    </content>
    <updated>2010-09-05T20:47:35Z</updated>
    <published>2010-09-05T14:10:00Z</published>
    <category scheme="http://www.blogger.com/atom/ns#" term="software"/>
    <category scheme="http://www.blogger.com/atom/ns#" term="scala"/>
    <author>
      <name>Yuvi Masory</name>
      <email>noreply@blogger.com</email>
      <uri>http://www.blogger.com/profile/02772244377867084155</uri>
    </author>
    <source>
      <id>tag:blogger.com,1999:blog-5448311202414367852</id>
      <author>
        <name>Yuvi Masory</name>
        <email>noreply@blogger.com</email>
        <uri>http://www.blogger.com/profile/02772244377867084155</uri>
      </author>
      <link href="http://blog.yuvimasory.com/feeds/posts/default" rel="http://schemas.google.com/g/2005#feed" type="application/atom+xml"/>
      <link href="http://www.blogger.com/feeds/5448311202414367852/posts/default/-/scala" rel="self" type="application/atom+xml"/>
      <link href="http://blog.yuvimasory.com/search/label/scala" rel="alternate" type="text/html"/>
      <link href="http://pubsubhubbub.appspot.com/" rel="hub" type="text/html"/>
      <title>Yuvi Masory - Blog</title>
      <updated>2010-09-08T15:08:10Z</updated>
    </source>
  </entry>

  <entry>
    <id>http://code.technically.us/post/1070752000</id>
    <link href="http://code.technically.us/post/1070752000" rel="alternate" type="text/html"/>
    <title>"a graphical overview over the Scala 2.8 Collections API types most relevant to Scala developers"</title>
    <summary type="xhtml"><div xmlns="http://www.w3.org/1999/xhtml">“a graphical overview over the Scala 2.8 Collections API types most relevant to Scala developers”<br/><br/> - <em><a href="http://www.decodified.com/scala/collections-api.xml">Scala 2.8 Collections API ← Decodified</a></em></div>
    </summary>
    <updated>2010-09-05T16:00:55Z</updated>
    <category term="Scala"/>
    <category term="Collections"/>
    <category term="Servicey"/>
    <category term="Diagrams"/>
    <category term="decodified"/>
    <source>
      <id>http://code.technically.us/</id>
      <author>
        <name>Coderspiel</name>
      </author>
      <link href="http://tumblr.superfeedr.com/" rel="hub" type="text/html"/>
      <link href="http://code.technically.us/" rel="alternate" type="text/html"/>
      <link href="http://code.technically.us/rss" rel="self" type="application/rss+xml"/>
      <title>Coderspiel</title>
      <updated>2010-09-09T03:00:39Z</updated>
    </source>
  </entry>

  <entry>
    <id>http://code.technically.us/post/1064610162</id>
    <link href="http://code.technically.us/post/1064610162" rel="alternate" type="text/html"/>
    <title>"Last week I got the chance to put my hands on some technologies I’ve been interested for some time..."</title>
    <summary type="xhtml"><div xmlns="http://www.w3.org/1999/xhtml">“Last week I got the chance to put my hands on some technologies I’ve been interested for some time now. I’ve created a basic 3D example of some fractals, and implemented it in 2D Canvas, WebGL and SPDE (Scala + Processing).”<br/><br/> - <em><a href="http://blog.thejit.org/2010/09/04/three-ways-to-make-3d/">Three ways to make 3D</a></em></div>
    </summary>
    <updated>2010-09-04T16:16:03Z</updated>
    <category term="Scala"/>
    <category term="Processing"/>
    <category term="Spde"/>
    <category term="Javascript"/>
    <category term="WebGL"/>
    <category term="OpenGL"/>
    <source>
      <id>http://code.technically.us/</id>
      <author>
        <name>Coderspiel</name>
      </author>
      <link href="http://tumblr.superfeedr.com/" rel="hub" type="text/html"/>
      <link href="http://code.technically.us/" rel="alternate" type="text/html"/>
      <link href="http://code.technically.us/rss" rel="self" type="application/rss+xml"/>
      <title>Coderspiel</title>
      <updated>2010-09-09T03:00:39Z</updated>
    </source>
  </entry>

  <entry>
    <id>tag:blogger.com,1999:blog-7317245822288637185.post-7811452684437212052</id>
    <link href="http://grahamhackingscala.blogspot.com/feeds/7811452684437212052/comments/default" rel="replies" type="application/atom+xml"/>
    <link href="http://grahamhackingscala.blogspot.com/2010/01/why-your-company-should-let-you-use.html#comment-form" rel="replies" type="text/html"/>
    <link href="http://www.blogger.com/feeds/7317245822288637185/posts/default/7811452684437212052?v=2" rel="edit" type="application/atom+xml"/>
    <link href="http://www.blogger.com/feeds/7317245822288637185/posts/default/7811452684437212052?v=2" rel="self" type="application/atom+xml"/>
    <link href="http://feedproxy.google.com/~r/blogspot/vnby/~3/RIONTGfre5s/why-your-company-should-let-you-use.html" rel="alternate" type="text/html"/>
    <title>Why Your Company Should Let You Use Scala at Work</title>
    <content type="xhtml"><div xmlns="http://www.w3.org/1999/xhtml"><span style="font-size: 130%; font-weight: bold;">Java at Work: An Increasingly Frustrating Experience</span><br/><br/>A colleague and I were writing a test in Java today and I had one of those "I can't believe it takes this much work to write this stupid function" moments. If you do any Scala programming but still do a lot of Java programming, you'll know exactly what I mean. I'll walk you through a mock of what we were doing and you can see why Scala just pummels Java when it comes to expressiveness. (Early warning: do not use the word "expressive" when trying to convince your manager to let you use Scala at work.)<br/><br/>So, here's the gist of the code that we were testing:<br/><pre class="brush: java"><br/>import java.util.ArrayList;<br/>import java.util.List;<br/><br/>class AccountSummaryService {<br/>    public List&lt;CustomerSummaryDTO&gt; getAccountSummaries() {<br/>        return new ArrayList&lt;CustomerSummaryDTO&gt;();<br/>    }<br/>}<br/><br/>class CustomerSummaryDTO {<br/>    private String name;<br/>    private List&lt;AccountSummaryDTO&gt; accountSummaries;<br/><br/>    public String getName() {<br/>        return name;<br/>    }<br/><br/>    public List&lt;AccountSummaryDTO&gt; getAccounts() {<br/>        return accountSummaries;<br/>    }<br/>}<br/><br/>class AccountSummaryDTO {<br/>    private String name;<br/>    private int balance;<br/><br/>    public String getName() {<br/>        return name;<br/>    }<br/><br/>    public int getBalance() {<br/>        return balance;<br/>    }<br/>}<br/></pre>and here's the gist of the test that we wrote:<pre class="brush: java"><br/>import org.junit.Test;<br/><br/>import java.util.List;<br/>import java.util.NoSuchElementException;<br/><br/>import static org.hamcrest.core.Is.is;<br/>import static org.junit.Assert.assertThat;<br/><br/>class AccountSummaryServiceJavaTest {<br/>    AccountSummaryService service = new AccountSummaryService();<br/><br/>    @Test<br/>    public void getAccountSummaries() {<br/>        List&lt;CustomerSummaryDTO&gt; result = service.getAccountSummaries();<br/>        assertThat(balanceFor("Customer 1", "Account #2", result), <br/>                   is(1000000));<br/>    }<br/><br/>    private int balanceFor(String customerName, String accountName, <br/>                           List&lt;CustomerSummaryDTO&gt; result) {<br/>        for (CustomerSummaryDTO customer : result) {<br/>            if (customer.getName().equals(customerName)) {<br/>                for (AccountSummaryDTO account : customer.getAccounts()) {<br/>                    if (account.getName().equals(accountName)) {<br/>                        return account.getBalance();<br/>                    }<br/>                }<br/>            }<br/>        }<br/>        throw new NoSuchElementException("Account not found");<br/>    }<br/>}<br/></pre>As you can see, I'm a bit of a fan of fluent interfaces, hence the use of Hamcrest matchers and the <code>balanceFor()</code> method. This makes for a nice, readable test, but boy is that <code>balanceFor()</code> method ugly! Considering the simple job it's doing, there is a lot of code and - the thing I especially hate - a lot of noise. I would say this code has a relatively low <a href="http://en.wikipedia.org/wiki/Signal-to-noise_ratio#Informal_use" target="_blank">signal-to-noise ratio</a>.<br/><br/>The lack of visual appeal isn't the only problem. Another problem is that, despite being trivial, it took more than a few seconds to write. An even more disturbing problem is that my colleague and I both spent another 30 seconds triple-checking this code to make sure it was doing what we wanted it to. Not because it's complex (it's not) or because we're stupid (we're not). We were checking it over because (a) it took too long to write for such a simple operation, so we thought maybe it could be simplified, and (b) there is so much noise in the code that it just LOOKED like a bear trap for stupid errors.<br/><br/>I quipped that the same function in Scala would be much shorter and easier to read. My colleague called me on it and asked what the Scala would look like, so I wrote some hacky Scala in a comment to give him the feel of it. It was, of course, slightly wrong, and turned out to be more complex than it needed to be, but I wrote it again when I got home and compiled it just to prove my point. Here's the <code>balanceFor()</code> method rewritten in Scala:<br/><pre class="brush: scala"><br/>  def balanceFor(customerName : String, accountName : String, result : <br/>                 Iterable[CustomerSummaryDTO]) = <br/>      result.find(_.getName == customerName).get<br/>        .getAccounts().find(_.getName == accountName).get<br/>        .getBalance<br/></pre>You can see straight away that this function is shorter. Just syntactically, using Scala has removed a lot of the noise: theres no type declarations in the implementation; there's no verbose but meaningless local variable names because we can use _ to create anonymous functions; we're able to use <code>==</code> instead of <code>.equals()</code> with the same effect; the exception is thrown by the API because <code>find()</code> returns an Option; and, thanks to the power of Scala's API, we can even lose the braces because the whole function is just one expression.<br/><br/>But its endearing qualities don't end at the reduced demands on screen lines and hard drive. The Scala implementation reads in a way that is so much closer to the intent of the function - so much closer than a for loop with a nested if, with a nested for, with a nested if, followed by four closing braces and a throw statement. The <code>find()</code> function expresses what we are trying to do exactly; to a reader attempting to comprehend the code, its simplicity is profound when compared to the for statement and if statement that combined do the same thing but are spread over two lines in the Java version.<br/><br/>To make a fair comparison, I will highlight that Scala has added one piece of noise to the implementation that wasn't present in the Java: the <code>.get</code> call at the end of each of the first two lines, used to access the contents of the <a href="http://www.scala-lang.org/docu/files/api/scala/Option.html" target="_blank">Option</a> returned by <code>find()</code>. To anyone who has read an introductory Scala book, this will make immediate sense and to anyone that hasn't even seen Scala before, a 30-second explanation of Option should make everything pretty clear.<br/><p style="background-color: #DDDDDD;"><span style="color: #DD0000;">Note:</span> Some people believe that you should never use the <code>.get</code> function on <code>Option</code> - never, ever! I don't agree with them absolutely. In general, this function is probably not a good one to call if you're writing production Scala code, but I think it can still be useful in certain circumstances. See the comments if you want to know more.</p><br/>For me, the best part about this code is that the combination of its succinctness, expressiveness and almost total lack of noise means that we wouldn't need to spend 30 seconds triple-checking it. Not only did it take such a short time to write that I could still remember the first key-stroke by the time I'd finished, but I can look at this code and <b>see</b> what it does without having to <b>read</b> it.<br/><br/><span style="font-size: 130%; font-weight: bold;">Hang On, I Thought This Blog Was About Using Scala at Work?</span><br/><br/>Actually, so far it's been about <i>not</i> using Scala at work, and how annoying that can be.<br/>How can we change this situation?<br/><br/>Well, imagine you go to your boss and you say, "Hey, Boss. Can we start using Scala?" and he says, "Why?" and you say, "Um, 'cause it's a functional language so it's more expressive and it has monads and everything's immutable so it might help us to write better multi-threaded code" and he'll say? ... "Get back to work".<br/><br/>Well, the silly little method above, along with the issues it solved, is a perfect little use case for why Scala could be great for your company's software development. Forget all the functional paradigms and monadic, higher-kinded academia - <a href="http://www.simpsoncrazy.com/scripts/itchy-scratchy-poochie" target="_blank">these are just buzz words that dumb people use to sound important</a>. (Kidding.) No, there are real, practical, business reasons your company should let you code in Scala. My experience, as demonstrated in the code here, is that Scala lets me write code <i>faster</i> and also <i>makes it harder for me to get things wrong</i>. Or, to rephrase that in managerese, it <b>increases output</b> and <b>improves quality</b>.<br/><br/>So, instead of pitching technical buzzwords at your boss, imagine trying this out: "Hey, Boss. How would you like it if I could write twice as much code in a day and have more confidence that it actually does what I intend it to?" Now you're speaking his language: Output and Quality. But why not go one better than imagining? Why not go and ask your boss now!<br/><br/>If your boss says YES, and you need to get up to speed with Scala, you'll probably want to grab one of these books:<br/><br/><p style="text-align: center; background-color: #666666; color: #FFFFFF;">From Amazon</p><br/><table><tbody><tr><td>&lt;iframe frameborder="0" marginheight="0" marginwidth="0" scrolling="no" src="http://rcm.amazon.com/e/cm?lt1=_blank&amp;amp;bc1=FFFFFF&amp;amp;IS2=1&amp;amp;npa=1&amp;amp;bg1=FFFFFF&amp;amp;fc1=000000&amp;amp;lc1=4444CC&amp;amp;t=belmontechno-20&amp;amp;o=1&amp;amp;p=8&amp;amp;l=as1&amp;amp;m=amazon&amp;amp;f=ifr&amp;amp;md=10FE9736YVPPT7A0FBG2&amp;amp;asins=0981531601" style="width:120px;height:240px;"&gt;&lt;/iframe&gt;</td><td>&lt;iframe frameborder="0" marginheight="0" marginwidth="0" scrolling="no" src="http://rcm.amazon.com/e/cm?lt1=_blank&amp;amp;bc1=FFFFFF&amp;amp;IS2=1&amp;amp;npa=1&amp;amp;bg1=FFFFFF&amp;amp;fc1=000000&amp;amp;lc1=4444CC&amp;amp;t=belmontechno-20&amp;amp;o=1&amp;amp;p=8&amp;amp;l=as1&amp;amp;m=amazon&amp;amp;f=ifr&amp;amp;md=10FE9736YVPPT7A0FBG2&amp;amp;asins=193435631X" style="width:120px;height:240px;"&gt;&lt;/iframe&gt;</td><td>&lt;iframe frameborder="0" marginheight="0" marginwidth="0" scrolling="no" src="http://rcm.amazon.com/e/cm?lt1=_blank&amp;amp;bc1=FFFFFF&amp;amp;IS2=1&amp;amp;npa=1&amp;amp;bg1=FFFFFF&amp;amp;fc1=000000&amp;amp;lc1=4444CC&amp;amp;t=belmontechno-20&amp;amp;o=1&amp;amp;p=8&amp;amp;l=as1&amp;amp;m=amazon&amp;amp;f=ifr&amp;amp;md=10FE9736YVPPT7A0FBG2&amp;amp;asins=0596155956" style="width:120px;height:240px;"&gt;&lt;/iframe&gt;</td><td>&lt;iframe frameborder="0" marginheight="0" marginwidth="0" scrolling="no" src="http://rcm.amazon.com/e/cm?lt1=_blank&amp;amp;bc1=FFFFFF&amp;amp;IS2=1&amp;amp;npa=1&amp;amp;bg1=FFFFFF&amp;amp;fc1=000000&amp;amp;lc1=4444CC&amp;amp;t=belmontechno-20&amp;amp;o=1&amp;amp;p=8&amp;amp;l=as1&amp;amp;m=amazon&amp;amp;f=ifr&amp;amp;md=10FE9736YVPPT7A0FBG2&amp;amp;asins=1430219890" style="width:120px;height:240px;"&gt;&lt;/iframe&gt;</td><td>&lt;iframe frameborder="0" marginheight="0" marginwidth="0" scrolling="no" src="http://rcm.amazon.com/e/cm?lt1=_blank&amp;amp;bc1=FFFFFF&amp;amp;IS2=1&amp;amp;npa=1&amp;amp;bg1=FFFFFF&amp;amp;fc1=000000&amp;amp;lc1=4444CC&amp;amp;t=belmontechno-20&amp;amp;o=1&amp;amp;p=8&amp;amp;l=as1&amp;amp;m=amazon&amp;amp;f=ifr&amp;amp;md=10FE9736YVPPT7A0FBG2&amp;amp;asins=143022844X" style="width:120px;height:240px;"&gt;&lt;/iframe&gt;</td></tr></tbody></table><br/><br/><p style="text-align: center; background-color: #666666; color: #FFFFFF;">From The Book Depository</p><br/><a href="http://www.bookdepository.co.uk/book/9780981531601/Programming-in-Scala/?a_aid=belmonttechnology" target="_blank">Programming in Scala - Martin Odersky, Lex Spoon &amp; Bill Venners (Artima)</a><br/><br/><a href="http://www.bookdepository.co.uk/book/9781934356319/Programming-Scala/?a_aid=belmonttechnology" target="_blank">Programming Scala - Venkat Subramaniam (The Pragmatic Programmers)</a><br/><br/><a href="http://www.bookdepository.co.uk/book/9780596155957/Programming-Scala/?a_aid=belmonttechnology" target="_blank">Programming Scala - Dean Wampler &amp; Alex Payne (O'Reilly)</a><br/><br/><a href="http://www.bookdepository.co.uk/book/9781430219897/Beginning-Scala/?a_aid=belmonttechnology" target="_blank">Beginner Scala - David Pollak (Apress)</a><br/><br/><a href="http://www.bookdepository.co.uk/book/9781430228448/Pro-Scala/?a_aid=belmonttechnology" target="_blank">Pro Scala - Gregory Meredith (Apress)</a><br/><br/><br/>Disclaimer:<span style="font-size: 80%;"><br/>It's not my intention to represent Scala as being better than Java for every project in every organisation, or for any particular one at all. Obviously there are many more issues to consider when adopting a language than just those presented here. My claims that Scala increases output and quality are based only on my own anecdotal observations and not on any empirical evidence. You should make your own investigations before making any commitment to using Scala in a commercial context.</span><div class="blogger-post-footer"><img alt="" height="1" src="https://blogger.googleusercontent.com/tracker/7317245822288637185-7811452684437212052?l=grahamhackingscala.blogspot.com" width="1"/></div>
<p><a href="http://feedads.g.doubleclick.net/~a/nA-LIV66bC6U-N7mir1Muy5cQKA/0/da"><img border="0" ismap="true" src="http://feedads.g.doubleclick.net/~a/nA-LIV66bC6U-N7mir1Muy5cQKA/0/di"/></a><br/>
<a href="http://feedads.g.doubleclick.net/~a/nA-LIV66bC6U-N7mir1Muy5cQKA/1/da"><img border="0" ismap="true" src="http://feedads.g.doubleclick.net/~a/nA-LIV66bC6U-N7mir1Muy5cQKA/1/di"/></a></p><img height="1" src="http://feeds.feedburner.com/~r/blogspot/vnby/~4/RIONTGfre5s" width="1"/></div>
    </content>
    <updated>2010-09-04T09:52:49Z</updated>
    <published>2010-01-29T22:40:00Z</published>
    <category scheme="http://www.blogger.com/atom/ns#" term="commercial"/>
    <category scheme="http://www.blogger.com/atom/ns#" term="fluent"/>
    <category scheme="http://www.blogger.com/atom/ns#" term="functional"/>
    <category scheme="http://www.blogger.com/atom/ns#" term="option"/>
    <category scheme="http://www.blogger.com/atom/ns#" term="find"/>
    <category scheme="http://www.blogger.com/atom/ns#" term="work"/>
    <category scheme="http://www.blogger.com/atom/ns#" term="real world"/>
    <category scheme="http://www.blogger.com/atom/ns#" term="books"/>
    <category scheme="http://www.blogger.com/atom/ns#" term="list"/>
    <category scheme="http://www.blogger.com/atom/ns#" term="test"/>
    <category scheme="http://www.blogger.com/atom/ns#" term="signal"/>
    <category scheme="http://www.blogger.com/atom/ns#" term="company"/>
    <category scheme="http://www.blogger.com/atom/ns#" term="comparison"/>
    <category scheme="http://www.blogger.com/atom/ns#" term="effective java"/>
    <category scheme="http://www.blogger.com/atom/ns#" term="example"/>
    <category scheme="http://www.blogger.com/atom/ns#" term="succint"/>
    <category scheme="http://www.blogger.com/atom/ns#" term="concise"/>
    <category scheme="http://www.blogger.com/atom/ns#" term="noise"/>
    <category scheme="http://www.blogger.com/atom/ns#" term="expressive"/>
    <category scheme="http://www.blogger.com/atom/ns#" term="scala"/><feedburner:origLink xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0">http://grahamhackingscala.blogspot.com/2010/01/why-your-company-should-let-you-use.html</feedburner:origLink>
    <author>
      <name>Grazer</name>
      <email>noreply@blogger.com</email>
      <uri>http://www.blogger.com/profile/00435359638152521056</uri>
    </author>
    <source>
      <id>tag:blogger.com,1999:blog-7317245822288637185</id>
      <author>
        <name>Grazer</name>
        <email>noreply@blogger.com</email>
        <uri>http://www.blogger.com/profile/00435359638152521056</uri>
      </author>
      <link href="http://grahamhackingscala.blogspot.com/feeds/posts/default" rel="http://schemas.google.com/g/2005#feed" type="application/atom+xml"/>
      <link href="http://grahamhackingscala.blogspot.com/" rel="alternate" type="text/html"/>
      <link href="http://feeds.feedburner.com/blogspot/vnby" rel="self" type="application/atom+xml"/>
      <link href="http://pubsubhubbub.appspot.com/" rel="hub" type="text/html"/>
      <subtitle>The point of "Graham Hacking Scala" is to share with you my knowledge of and experience with the Scala programming language. The blog will contain everything from introductions to basic features through to in-depth analysis of complex techniques and problems. When I make mistakes, you will learn from my mistakes. When I discover cool features, you will learn about them, too.</subtitle>
      <title>Graham Hacking Scala</title>
      <updated>2010-09-04T16:58:00Z</updated>
    </source>
  </entry>

  <entry>
    <id>tag:blogger.com,1999:blog-7317245822288637185.post-2558806089115520923</id>
    <link href="http://grahamhackingscala.blogspot.com/feeds/2558806089115520923/comments/default" rel="replies" type="application/atom+xml"/>
    <link href="http://grahamhackingscala.blogspot.com/2010/01/scala-spring-hibernate-maven-webapp-how.html#comment-form" rel="replies" type="text/html"/>
    <link href="http://www.blogger.com/feeds/7317245822288637185/posts/default/2558806089115520923?v=2" rel="edit" type="application/atom+xml"/>
    <link href="http://www.blogger.com/feeds/7317245822288637185/posts/default/2558806089115520923?v=2" rel="self" type="application/atom+xml"/>
    <link href="http://feedproxy.google.com/~r/blogspot/vnby/~3/Ey9wylQB4Jo/scala-spring-hibernate-maven-webapp-how.html" rel="alternate" type="text/html"/>
    <title>How To Create a Webapp with Scala, Spring, Hibernate and Maven</title>
    <content type="xhtml"><div xmlns="http://www.w3.org/1999/xhtml"><span style="font-size: 130%;"><span style="font-weight: bold;">The Technologies</span></span><br/><br/>So, this post is simply a recipe for combining four of today's most popular technologies: Spring, Hibernate, Maven and Scala.<br/><br/>In case you're new to some of these technologies, here's a REALLY quick overview:<br/><br/><b>Spring</b> is a framework for creating enterprise applications that uses Inversion of Control, Dependency Injection, Aspect-Oriented Programming (including annotation-based transaction boundaries) and lots of flexible, highly-extensible components for building pretty much anything. Its Model-View-Controller (MVC) web framework has been a popular replacement for Struts. <br/><br/><b>Hibernate</b> is an Object-Relational Mapping library, used to store data from Java objects into relational databases (and retrieve it again).<br/><br/><b>Maven</b> is a Java-based and -focussed build tool that uses a common project lifecycle and a declarative Project Object Model (POM) to make it simple to build applications by defining only what needs to happen, rather than how it happens (which remains in the implementation details of its plugins).<br/><br/><b>Scala</b> is a Functional/Object-Oriented hybrid language that executes on the Java Virtual Machine (JVM) and is becoming increasingly popular, especially with Java developers, mostly due to its concise syntax, static typing and seamless integration with the Java SE API.<br/><br/><span style="font-size: 130%;"><span style="font-weight: bold;">The Task</span></span><br/><br/>The task is to write a simple webapp that can persist and retrieve an entity. The goal is to use the latest of everything, including Scala 2.8, Hibernate 3.2.7 with annotations and Spring 3 and it's annotation-based controllers for creating REST-ful webapps.<br/><br/>The first part of this tutorial is basically just a diary of the steps I took to create a working application using Maven, Scala, Spring and Hibernate. I won't do a lot of explaining because different readers will obviously have different knowledge about different technologies, but I've documented every single web page that gave me a useful piece of information in putting the whole thing together.<br/><br/>The second part is a documentation of all the little things that went wrong while creating the "how to". Including these in the main introduction would just be a distraction but I'm sure the fixes I had to discover and correct will be useful to a few people scouring the internet for solutions one day.<br/><br/>Enough chatter, let's write some code…<br/><br/>No, wait!<br/>Let's GENERATE some code! :)<br/><br/><span style="font-size: 130%;"><span style="font-weight: bold;">Step 1: Use Maven to Create a Project</span></span><br/><br/>If you don't already have Maven installed, you'll need to download and install it and put its bin/ directory on your path.<br/><br/><b>References:</b><br/><a href="http://maven.apache.org/download.html" target="_blank">Download Maven</a><br/><br/>I already had it installed (although I don't remember installing it - is it standard on a Mac?) so I went to the directory where I wanted the project to live and created a new Maven project using the Scala archetype with this command:<br/><pre class="brush: text"><br/>mvn org.apache.maven.plugins:maven-archetype-plugin:1.0-alpha-7:create \<br/>-DarchetypeGroupId=org.scala-tools.archetypes \<br/>-DarchetypeArtifactId=scala-archetype-simple \<br/>-DarchetypeVersion=1.1 \<br/>-DremoteRepositories=http://scala-tools.org/repo-releases \<br/>-DgroupId=au.com.belmonttechnology -DartifactId=scala-spring-hibernate<br/></pre><br/><b>References:</b><br/><a href="http://scala-blogs.org/2008/01/maven-for-scala.html" target="_blank">Scala Blogs: maven for scala</a><br/><br/>Then I went into the directory and built the project:<br/><pre class="brush: text"><br/>mvn clean package<br/></pre><br/>After downloading lots of plugin code, it successfully compiled the App and AppTest classes and then the AppTest.testKO test case failed. No need to panic - the implementation of this generated Test shows that it's meant to fail. It proves that Maven is running the test.<br/><br/>Too easy. Onwards and upwards...<br/><br/><span style="font-size: 130%;"><span style="font-weight: bold;">Step 2: Get Scala and Maven Working in Your IDE</span></span><br/><br/>I'm using <a href="http://www.jetbrains.com/idea/download/" target="_blank">IntelliJ IDEA 9 Community Edition</a> (it's free!). I was dead-simple to create a new IDEA project using the Maven POM that was just generated. Here are the steps:<br/><br/>1. New Project<br/>2. Import project from external model<br/>3. Maven<br/>4. Choose directory<br/>5a. Only tick 'Import Maven projects automatically' and 'Use Maven output directories'<br/>5b. Use 'process-test-resources'<br/>6. Finish!<br/><br/>You'll also need to make sure you've got a Scala plugin for your IDE installed and working. In IDEA, you can get one just by going into the Plugins config pan, searching for Scala and downloading the one that pops up.<br/><br/>To make sure the IDE was set up properly, I opened the <code>App</code> class, and changed it to look like this:<br/><pre class="brush: scala"><br/>object App {<br/>  def main(args: Array[String]) {<br/>    println( "Hello World!" );<br/>  }<br/>}<br/></pre>and then ran it (in IDEA use: CTRL-SHIFT-F10)<br/><br/>I like to live on the edge, and I noticed that the Scala version that the Maven archetype had delivered me was 2.6.1. Pfh! <br/><br/>So, I opened up <a href="http://scala-tools.org/repo-releases/org/scala-lang/scala-library/" target="_blank">http://scala-tools.org/repo-releases/org/scala-lang/scala-library/</a> in Firefox and found the latest and greatest (and hopefully somewhat stable) Scala release version, which was 2.8.0.Beta1-RC7 at the time of writing. I copied this version into the top of pom.xml, where the archetype had written:<br/><pre class="brush: xml"><br/>&lt;scala.version&gt;2.6.1&lt;/scala.version&gt;<br/></pre>I ran the <code>App</code> class again to make sure it's still working<br/><br/>Having proved that the <code>App</code> class was working - I DELETED IT!<br/><br/><span style="font-size: 130%;"><span style="font-weight: bold;">Step 3: Create a Spring Web Application</span></span><br/><br/>I added the following two entries into the <code>&lt;repositories&gt;</code> section of the POM:<br/><pre class="brush: xml"><br/>&lt;repository&gt;<br/>    &lt;id&gt;com.springsource.repository.bundles.release&lt;/id&gt;<br/>    &lt;name&gt;EBR Spring Release Repository&lt;/name&gt;<br/>    &lt;url&gt;http://repository.springsource.com/maven/bundles/release&lt;/url&gt;<br/>&lt;/repository&gt;<br/>&lt;repository&gt;<br/>    &lt;id&gt;com.springsource.repository.bundles.external&lt;/id&gt;<br/>    &lt;name&gt;EBR External Release Repository&lt;/name&gt;<br/>    &lt;url&gt;http://repository.springsource.com/maven/bundles/external&lt;/url&gt;<br/>&lt;/repository&gt;<br/></pre><br/><b>References:</b><br/><a href="http://blog.springsource.com/2009/12/02/obtaining-spring-3-artifacts-with-maven/" target="_blank">Obtaining Spring 3 Artifacts with Maven</a><br/><br/>Then I added the following line to the <code>&lt;properties&gt;</code> section:<br/><pre class="brush: xml"><br/>&lt;org.springframework.version&gt;3.0.0.RELEASE&lt;/org.springframework.version&gt;<br/></pre><br/>and added the following dependencies to the <code>&lt;dependencies&gt;</code> section:<br/><pre class="brush: xml"><br/>&lt;dependency&gt;<br/>  &lt;groupId&gt;org.springframework&lt;/groupId&gt;<br/>  &lt;artifactId&gt;org.springframework.context&lt;/artifactId&gt;<br/>  &lt;version&gt;${org.springframework.version}&lt;/version&gt;<br/>&lt;/dependency&gt;<br/><br/>&lt;dependency&gt;<br/>  &lt;groupId&gt;org.springframework&lt;/groupId&gt;<br/>  &lt;artifactId&gt;org.springframework.transaction&lt;/artifactId&gt;<br/>  &lt;version&gt;${org.springframework.version}&lt;/version&gt;<br/>&lt;/dependency&gt;<br/><br/>&lt;dependency&gt;<br/>  &lt;groupId&gt;org.springframework&lt;/groupId&gt;<br/>  &lt;artifactId&gt;org.springframework.orm&lt;/artifactId&gt;<br/>  &lt;version&gt;${org.springframework.version}&lt;/version&gt;<br/>&lt;/dependency&gt;<br/><br/>&lt;dependency&gt;<br/>  &lt;groupId&gt;org.springframework&lt;/groupId&gt;<br/>  &lt;artifactId&gt;org.springframework.web&lt;/artifactId&gt;<br/>  &lt;version&gt;${org.springframework.version}&lt;/version&gt;<br/>&lt;/dependency&gt;<br/><br/>&lt;dependency&gt;<br/>  &lt;groupId&gt;org.springframework&lt;/groupId&gt;<br/>  &lt;artifactId&gt;org.springframework.web.servlet&lt;/artifactId&gt;<br/>  &lt;version&gt;${org.springframework.version}&lt;/version&gt;<br/>&lt;/dependency&gt;<br/><br/>&lt;dependency&gt;<br/>    &lt;groupId&gt;javax.servlet&lt;/groupId&gt;<br/>    &lt;artifactId&gt;servlet-api&lt;/artifactId&gt;<br/>    &lt;version&gt;2.5&lt;/version&gt;<br/>    &lt;scope&gt;provided&lt;/scope&gt;<br/>&lt;/dependency&gt;<br/><br/>&lt;dependency&gt;<br/>    &lt;groupId&gt;commons-logging&lt;/groupId&gt;<br/>    &lt;artifactId&gt;commons-logging&lt;/artifactId&gt;<br/>    &lt;version&gt;1.1.1&lt;/version&gt;<br/>&lt;/dependency&gt;<br/></pre><br/>I wanted to get Spring working before I tried to integrate Hibernate, so I created a new package, <code>au.com.belmonttechnology.spring.web</code>, and created a new Scala class in there called <code>HelloWorldController</code>, and wrote this code:<br/><pre class="brush: scala"><br/>@Controller<br/>class HelloWorldController {<br/>  @RequestMapping(Array("/hello.html"))<br/>  def showHello = "helloPage"<br/>}<br/></pre><br/><b>References:</b><br/><a href="http://static.springsource.org/spring/docs/2.5.6/reference/mvc.html#mvc-ann-requestmapping" target="_blank">Mapping requests with @RequestMapping</a><br/><br/>I ran <code>mvn clean package</code> again to make sure this little guy compiled.<br/><br/>Then I created a src/main/webapp/WEB-INF directory and created a web.xml file with a basic <code>DispatcherServlet</code> setup:<br/><pre class="brush: xml"><br/>&lt;?xml version="1.0" encoding="UTF-8"?&gt;<br/>&lt;web-app xmlns="http://java.sun.com/xml/ns/javaee"<br/>         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"<br/>         xsi:schemaLocation="<br/>           http://java.sun.com/xml/ns/javaee <br/>           http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"<br/>         id="scala-spring-hibernate"<br/>         version="2.5"&gt;<br/><br/>    &lt;servlet&gt;<br/>        &lt;servlet-name&gt;dispatcher&lt;/servlet-name&gt;<br/>        &lt;servlet-class&gt;<br/>            org.springframework.web.servlet.DispatcherServlet<br/>        &lt;/servlet-class&gt;<br/>        &lt;init-param&gt;<br/>            &lt;param-name&gt;contextConfigLocation&lt;/param-name&gt;<br/>            &lt;param-value&gt;/WEB-INF/web-context.xml&lt;/param-value&gt;<br/>        &lt;/init-param&gt;<br/>        &lt;load-on-startup&gt;1&lt;/load-on-startup&gt;<br/>    &lt;/servlet&gt;<br/><br/>    &lt;servlet-mapping&gt;<br/>        &lt;servlet-name&gt;dispatcher&lt;/servlet-name&gt;<br/>        &lt;url-pattern&gt;*.html&lt;/url-pattern&gt;<br/>    &lt;/servlet-mapping&gt;<br/><br/>&lt;/web-app&gt;<br/></pre><br/><b>References:</b><br/><a href="http://static.springsource.org/spring/docs/2.5.6/reference/mvc.html#mvc-servlet" target="_blank">DispatcherServlet reference documentation</a><br/><a href="http://static.springsource.org/spring/docs/3.0.x/api/org/springframework/web/servlet/DispatcherServlet.html" target="_blank">DispatcherServlet javadoc</a><br/><a href="http://www.javabeat.net/articles/18-introduction-to-spring-mvc-web-framework-web-tier-1.html" target="_blank">Introduction to Spring MVC Web Framework</a><br/><a href="http://www.jroller.com/ndpar/entry/jstl_12_jetty_plugin" target="_blank">JSTL 1.2 and maven-jetty-plugin</a><br/><br/>Then I created the web-context.xml file that is used to initialise the Spring context for the <code>DispatcherServlet</code>. I set up a component-scan for the package that contains the HelloWorldController and inserted the same UrlBasedViewResolver configuration that everyone else in the world is using:<br/><pre class="brush: xml"><br/>&lt;?xml version="1.0" encoding="UTF-8"?&gt;<br/>&lt;beans xmlns="http://www.springframework.org/schema/beans"<br/>       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"<br/>       xmlns:context="http://www.springframework.org/schema/context"<br/>       xsi:schemaLocation="<br/>        http://www.springframework.org/schema/beans <br/>        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd<br/>        http://www.springframework.org/schema/context <br/>        http://www.springframework.org/schema/context/spring-context-3.0.xsd"&gt;<br/><br/>    &lt;context:component-scan <br/>        base-package="au.com.belmonttechnology.spring.web"/&gt;<br/><br/>    &lt;bean id="viewResolver"<br/>          class="org.springframework.web.servlet.view.UrlBasedViewResolver"&gt;<br/>        &lt;property name="viewClass"<br/>            value="org.springframework.web.servlet.view.JstlView"/&gt;<br/>        &lt;property name="prefix" value="/WEB-INF/jsp/"/&gt;<br/>        &lt;property name="suffix" value=".jsp"/&gt;<br/>    &lt;/bean&gt;<br/><br/>&lt;/beans&gt;<br/></pre><br/><b>References:</b><br/><a href="http://wheelersoftware.com/articles/spring-autowiring-annotations-3.html" target="_blank">Annotation-Based Autowiring in Spring 2.5</a><br/><a href="http://static.springsource.org/spring/docs/2.5.6/reference/mvc.html#mvc-annotation" target="_blank">Annotation-based controller configuration</a><br/><a href="http://static.springsource.org/spring/docs/2.5.6/reference/mvc.html#mvc-viewresolver" target="_blank">Spring Web MVC Views and resolving them</a><br/><br/>Then I created the JSP that the <code>HelloWorldController</code> was returning as it's view: src/main/webapp/WEB-INF/jsp/helloPage.jsp<br/><pre class="brush: xml"><br/>&lt;%@page contentType="text/html;"%&gt;<br/>&lt;html&gt;<br/>&lt;body&gt;<br/>    &lt;h1&gt;Hello from ${pageContext.request.serverName}&lt;/h1&gt;<br/>&lt;/body&gt;<br/>&lt;/html&gt;<br/></pre><br/><b>References:</b><br/><a href="http://www.informit.com/articles/article.aspx?p=30946&amp;seqNum=7" target="_blank">JSTL Implicit Objects</a><br/><a href="http://java.sun.com/j2ee/sdk_1.3/techdocs/api/javax/servlet/ServletRequest.html" target="_blank">ServletRequest javadoc</a><br/><br/>And, finally, I changed the POM's packaging to be 'war':<br/><pre class="brush: xml"><br/>    &lt;packaging&gt;war&lt;/packaging&gt;<br/></pre><br/>At this point, I was able to  <code>mvn clean install</code> the project and everything builds, but there's no way of running the webapp...<br/><br/><span style="font-size: 130%;"><span style="font-weight: bold;">Step 4: Start the Webapp with Maven using the Jetty Plugin</span></span><br/><br/>One of the easiest ways I've found of getting a webapp to run for testing is to use the Jetty Maven Plugin. All I had to do was add the Jetty plugin to the POM:<br/><pre class="brush: xml"><br/>&lt;plugin&gt;<br/>  &lt;groupId&gt;org.mortbay.jetty&lt;/groupId&gt;<br/>  &lt;artifactId&gt;jetty-maven-plugin&lt;/artifactId&gt;<br/>  &lt;version&gt;7.0.2.v20100331&lt;/version&gt;<br/>&lt;/plugin&gt;<br/></pre><br/><b>References:</b><br/><a href="http://wiki.eclipse.org/Jetty/Feature/Jetty_Maven_Plugin" target="_blank">Jetty Maven Plugin</a><br/><br/>Then on the command line I simply ran:<br/><pre class="brush: text"><br/>mvn clean package jetty:run <br/></pre>and it all started up brilliantly.<br/>I accessed http://localhost:8080/hello.html and saw a beautiful thing:<br/><br/>Hello from localhost<br/><br/>So, with my Spring 3 / REST / Scala app running on Jetty, I moved onto Hibernate…<br/><br/><span style="font-size: 130%;"><span style="font-weight: bold;">Step 5: Get Hibernate Running in Spring</span></span><br/><br/>I added a dependency for the latest version of Hibernate and Hibernate Annotations to the POM:<br/><pre class="brush: xml"><br/>&lt;dependency&gt;<br/>    &lt;groupId&gt;org.hibernate&lt;/groupId&gt;<br/>    &lt;artifactId&gt;hibernate&lt;/artifactId&gt;<br/>    &lt;version&gt;3.4.0.GA&lt;/version&gt;<br/>    &lt;exclusions&gt;<br/>        &lt;exclusion&gt;<br/>            &lt;groupId&gt;javax.transaction&lt;/groupId&gt;<br/>            &lt;artifactId&gt;jta&lt;/artifactId&gt;<br/>        &lt;/exclusion&gt;<br/>    &lt;/exclusions&gt;<br/>&lt;/dependency&gt;<br/>&lt;dependency&gt;<br/>    &lt;groupId&gt;org.hibernate&lt;/groupId&gt;<br/>    &lt;artifactId&gt;hibernate-annotations&lt;/artifactId&gt;<br/>    &lt;version&gt;3.4.0.GA&lt;/version&gt;<br/>&lt;/dependency&gt;<br/></pre>I also added a couple of dependencies that Hibernate would need:<br/><pre class="brush: xml"><br/>        &lt;dependency&gt;<br/>            &lt;groupId&gt;org.slf4j&lt;/groupId&gt;<br/>            &lt;artifactId&gt;slf4j-api&lt;/artifactId&gt;<br/>            &lt;version&gt;1.5.8&lt;/version&gt;<br/>        &lt;/dependency&gt;<br/><br/>        &lt;dependency&gt;<br/>            &lt;groupId&gt;org.slf4j&lt;/groupId&gt;<br/>            &lt;artifactId&gt;slf4j-jdk14&lt;/artifactId&gt;<br/>            &lt;version&gt;1.5.8&lt;/version&gt;<br/>        &lt;/dependency&gt;<br/></pre>Then I created a very simple Hibernate <code>@Entity</code> class in Scala:<br/><pre class="brush: scala"><br/>package au.com.belmonttechnology.data<br/><br/>import javax.persistence.{GeneratedValue, Id, Entity}<br/>import reflect.BeanProperty<br/><br/>@Entity<br/>class Customer() {<br/>  @Id @GeneratedValue<br/>  var id: Long = 0<br/><br/>  @BeanProperty<br/>  var name: String = null;<br/>}<br/></pre><br/><b>References:</b><br/><a href="http://docs.jboss.org/hibernate/stable/annotations/reference/en/html/" target="_blank">Hibernate Annotations</a><br/><a href="http://programming-scala.labs.oreilly.com/ch14.html#JavaBeanProperties" target="_blank">JavaBean Properties in Scala</a><br/><br/>Next, I created a controller that would be able to serve a "Create New Customer" form, receive the POST submission from the form and redirect to a JSP that would display the newly-stored entity:<br/><pre class="brush: scala"><br/>package au.com.belmonttechnology.spring.web<br/><br/>import org.springframework.stereotype.Controller<br/>import au.com.belmonttechnology.data.Customer<br/>import org.springframework.beans.factory.annotation.Autowired<br/>import org.hibernate.SessionFactory<br/>import org.springframework.transaction.annotation.Transactional<br/>import org.springframework.web.bind.annotation.{PathVariable, ModelAttribute, RequestMapping}<br/>import org.springframework.web.bind.annotation.RequestMethod._<br/>import org.springframework.web.servlet.ModelAndView<br/><br/>@Controller<br/>class CustomerController {<br/>  implicit def sessionFactory2Session(sf: SessionFactory) = <br/>    sf.getCurrentSession();<br/><br/>  @Autowired<br/>  var sessionFactory: SessionFactory = null<br/><br/>  @ModelAttribute("command")<br/>  def createCustomerForFormBinding = new Customer<br/><br/>  @RequestMapping(value = Array("/customers/new"), method = Array(GET))<br/>  def showNewCustomerForm() = "newCustomer"<br/><br/>  @Transactional<br/>  @RequestMapping(value = Array("/customers/new"), method = Array(POST))<br/>  def createNewCustomer(@ModelAttribute("command") customer: Customer) =<br/>    "redirect:/customers/" + sessionFactory.save(customer) + ".html"<br/><br/>  @Transactional(readOnly = true)<br/>  @RequestMapping(<br/>    value = Array("/customers/{customerId}"), method = Array(GET))<br/>  def viewCustomer(@PathVariable customerId: Long) =<br/>    new ModelAndView("customer", "customer", <br/>      sessionFactory.get(classOf[Customer], customerId))<br/>}<br/></pre><br/><b>References:</b><br/><a href="http://static.springsource.org/spring/docs/2.5.x/reference/beans.html#beans-autowired-annotation" target="_blank">Spring @Autowired Annotation</a><br/><a href="http://static.springsource.org/spring/docs/2.5.6/reference/mvc.html#mvc-annotation" target="_blank">Annotation-based controller configuration</a><br/><a href="https://www.hibernate.org/hib_docs/v3/api/org/hibernate/Session.html" target="_blank">Hibernate Session javadoc</a><br/><a href="http://static.springsource.org/spring/docs/2.0.x/reference/transaction.html#tx-decl-explained" target="_blank">Understanding the Spring Framework's declarative transaction implementation</a><br/><a href="http://stackoverflow.com/questions/1135248/scala-equivalent-of-java-java-lang-classt-object" target="_blank">Scala for accessing a Class at runtime</a><br/><a href="http://static.springsource.org/spring/docs/3.0.x/api/org/springframework/web/servlet/ModelAndView.html" target="_blank">Spring ModelAndView javadoc</a><br/><br/>Then I created JSPs to match the views that I'd specified in the controller - newCustomer.jsp for submitting a POST to create a new Customer in the database:<br/><pre class="brush: xml"><br/>&lt;%@page contentType="text/html;"%&gt;<br/>&lt;%@taglib prefix="form" uri="http://www.springframework.org/tags/form" %&gt;<br/>&lt;html&gt;<br/>&lt;body&gt;<br/>    &lt;h1&gt;New Customer&lt;/h1&gt;<br/>    &lt;form:form&gt;<br/>        &lt;form:label path="name"&gt;Name&lt;/form:label&gt;<br/>        &lt;form:input path="name"/&gt;<br/>        &lt;input type="submit" label="Create Customer"/&gt;       <br/>    &lt;/form:form&gt;<br/>&lt;/body&gt;<br/>&lt;/html&gt;<br/></pre>and customer.jsp for viewing a <code>Customer</code> entity that's been retrieved from the database:<br/><pre class="brush: xml"><br/>&lt;%@page contentType="text/html;"%&gt;<br/>&lt;html&gt;<br/>&lt;body&gt;<br/>    &lt;h1&gt;${customer.name}&lt;/h1&gt;<br/>    &lt;p&gt;Might I suggest enhancing the system to support more than just a customer's name?&lt;/p&gt;<br/>&lt;/body&gt;<br/>&lt;/html&gt;<br/></pre><b>References:</b><br/><a href="http://static.springsource.org/spring/docs/3.0.x/reference/html/view.html#view-jsp-formtaglib" target="_blank">Spring Form Tag Library</a><br/><br/>I decided I need a quick and dirty in-memory database to test with, so I added the dependency for HSQLDB to the POM, as well as the Apache Commons Database Connection Pool:<br/><pre class="brush: xml"><br/>        &lt;dependency&gt;<br/>            &lt;groupId&gt;org.hsqldb&lt;/groupId&gt;<br/>            &lt;artifactId&gt;hsqldb&lt;/artifactId&gt;<br/>            &lt;version&gt;1.8.0.10&lt;/version&gt;<br/>        &lt;/dependency&gt;<br/>        &lt;dependency&gt;<br/>            &lt;groupId&gt;commons-dbcp&lt;/groupId&gt;<br/>            &lt;artifactId&gt;commons-dbcp&lt;/artifactId&gt;<br/>            &lt;version&gt;1.2&lt;/version&gt;<br/>        &lt;/dependency&gt;<br/></pre>Then I wrote the Spring config for Hibernate, and a BasicDataSource (using HSQLDB) in a file called spring-context.xml…<br/><pre class="brush: xml"><br/>&lt;?xml version="1.0" encoding="UTF-8"?&gt;<br/>&lt;beans xmlns="http://www.springframework.org/schema/beans"<br/>       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"<br/>       xmlns:context="http://www.springframework.org/schema/context"<br/>       xmlns:tx="http://www.springframework.org/schema/tx"<br/>       xsi:schemaLocation="<br/>        http://www.springframework.org/schema/beans<br/>        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd<br/>        http://www.springframework.org/schema/context<br/>        http://www.springframework.org/schema/context/spring-context-3.0.xsd<br/>        http://www.springframework.org/schema/tx<br/>        http://www.springframework.org/schema/tx/spring-tx-3.0.xsd"&gt;<br/><br/>    &lt;tx:annotation-driven/&gt;<br/><br/>    &lt;bean id="dataSource"<br/>             class="org.apache.commons.dbcp.BasicDataSource" <br/>             destroy-method="close"&gt;<br/>        &lt;property name="driverClassName" value="org.hsqldb.jdbcDriver"/&gt;<br/>        &lt;property name="url" value="jdbc:hsqldb:mem:scala-spring-hibernate"/&gt;<br/>        &lt;property name="username" value="sa"/&gt;<br/>        &lt;property name="password" value=""/&gt;<br/>    &lt;/bean&gt;<br/><br/>    &lt;bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"&gt;<br/>        &lt;property name="dataSource" ref="dataSource"/&gt;<br/>        &lt;property name="annotatedClasses"&gt;<br/>            &lt;list&gt;<br/>                &lt;value&gt;au.com.belmonttechnology.data.Customer&lt;/value&gt;<br/>            &lt;/list&gt;<br/>        &lt;/property&gt;<br/>        &lt;property name="hibernateProperties"&gt;<br/>            &lt;props&gt;<br/>                &lt;prop key="hibernate.dialect"&gt;<br/>                    org.hibernate.dialect.HSQLDialect<br/>                &lt;/prop&gt;<br/>                &lt;prop key="hibernate.show_sql"&gt;true&lt;/prop&gt;<br/>                &lt;prop key="hibernate.hbm2ddl.auto"&gt;create&lt;/prop&gt;<br/>            &lt;/props&gt;<br/>        &lt;/property&gt;<br/>    &lt;/bean&gt;<br/>&lt;/beans&gt;<br/></pre>.. and wired it into the web.xml using Spring's ContextLoaderListener:<br/><pre class="brush: xml"><br/>    &lt;context-param&gt;<br/>        &lt;param-name&gt;contextConfigLocation&lt;/param-name&gt;<br/>        &lt;param-value&gt;/WEB-INF/spring-context.xml&lt;/param-value&gt;<br/>    &lt;/context-param&gt;<br/><br/>    &lt;listener&gt;<br/>        &lt;listener-class&gt;<br/>            org.springframework.web.context.ContextLoaderListener<br/>        &lt;/listener-class&gt;<br/>    &lt;/listener&gt;<br/></pre>Lastly, I added an <code>OpenSessionInViewInterceptor</code> into the Spring configuration in web-context.xml and specified this as an interceptor on the <code>DefaultAnnotationHandlerMapping</code>:<br/><pre class="brush: xml"><br/>...<br/><br/>    &lt;bean id="openSessionInViewInterceptor"<br/>          class="org.springframework.orm.hibernate3.support.OpenSessionInViewInterceptor"&gt;<br/>        &lt;property name="sessionFactory" ref="sessionFactory"/&gt;<br/>    &lt;/bean&gt;<br/><br/>    &lt;bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping"&gt;<br/>        &lt;property name="interceptors"&gt;<br/>            &lt;list&gt;&lt;ref bean="openSessionInViewInterceptor"/&gt;&lt;/list&gt;<br/>        &lt;/property&gt;<br/>    &lt;/bean&gt;<br/><br/>...<br/></pre><br/><br/><b>References:</b><br/><a href="http://static.springsource.org/spring/docs/2.0.x/reference/transaction.html#tx-decl-explained" target="_blank">Understanding the Spring Framework's declarative transaction implementation</a><br/><a href="http://www.vaannila.com/spring/spring-hibernate-integration-1.html" target="_blank">Spring Hibernate Tutorial</a><br/><a href="http://www.theserverside.com/tt/articles/article.tss?l=UnitTesting" target="_blank">Unit-Testing Hibernate With HSQLDB</a><br/><a href="http://www.javabeat.net/articles/18-introduction-to-spring-mvc-web-framework-web-tier-1.html" target="_blank">Introduction to Spring MVC Web Framework</a><br/><a href="http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/orm/hibernate3/support/OpenSessionInViewInterceptor.html" target="_blank">OpenSessionInViewInterceptor</a><br/><br/>Then I fired it all up again with mvn clean package jetty:run, browsed to http://localhost:8080/customers/new.html and voila! I happily spent the rest of my evening delighting in entering new customers into my in-memory database. (Not.)<br/><br/>If you'd like to get your hands on this fantastic new application, you can <a href="http://www.belmonttechnology.com.au/code/grahamhackingscala/scala-spring-hibernate-maven-webapp.zip" target="_blank">download the source code from Belmont Technology (MIT licence)</a>.<br/><br/>Here's some books you might find useful if you plan to go further with Spring, Hibernate, Scala or Maven:<br/><p style="text-align: center; background-color: #666666; color: #FFFFFF;">From Amazon</p><br/><table><tbody><tr><td>&lt;iframe frameborder="0" marginheight="0" marginwidth="0" scrolling="no" src="http://rcm.amazon.com/e/cm?lt1=_blank&amp;amp;bc1=FFFFFF&amp;amp;IS2=1&amp;amp;npa=1&amp;amp;bg1=FFFFFF&amp;amp;fc1=000000&amp;amp;lc1=4444CC&amp;amp;t=belmontechno-20&amp;amp;o=1&amp;amp;p=8&amp;amp;l=as1&amp;amp;m=amazon&amp;amp;f=ifr&amp;amp;md=10FE9736YVPPT7A0FBG2&amp;amp;asins=1933988134" style="width:120px;height:240px;"&gt;&lt;/iframe&gt;</td><td>&lt;iframe frameborder="0" marginheight="0" marginwidth="0" scrolling="no" src="http://rcm.amazon.com/e/cm?lt1=_blank&amp;amp;bc1=FFFFFF&amp;amp;IS2=1&amp;amp;npa=1&amp;amp;bg1=FFFFFF&amp;amp;fc1=000000&amp;amp;lc1=4444CC&amp;amp;t=belmontechno-20&amp;amp;o=1&amp;amp;p=8&amp;amp;l=as1&amp;amp;m=amazon&amp;amp;f=ifr&amp;amp;md=10FE9736YVPPT7A0FBG2&amp;amp;asins=193239415X" style="width:120px;height:240px;"&gt;&lt;/iframe&gt;</td><td>&lt;iframe frameborder="0" marginheight="0" marginwidth="0" scrolling="no" src="http://rcm.amazon.com/e/cm?lt1=_blank&amp;amp;bc1=FFFFFF&amp;amp;IS2=1&amp;amp;npa=1&amp;amp;bg1=FFFFFF&amp;amp;fc1=000000&amp;amp;lc1=4444CC&amp;amp;t=belmontechno-20&amp;amp;o=1&amp;amp;p=8&amp;amp;l=as1&amp;amp;m=amazon&amp;amp;f=ifr&amp;amp;md=10FE9736YVPPT7A0FBG2&amp;amp;asins=1430224991" style="width:120px;height:240px;"&gt;&lt;/iframe&gt;</td><td>&lt;iframe frameborder="0" marginheight="0" marginwidth="0" scrolling="no" src="http://rcm.amazon.com/e/cm?lt1=_blank&amp;amp;bc1=FFFFFF&amp;amp;IS2=1&amp;amp;npa=1&amp;amp;bg1=FFFFFF&amp;amp;fc1=000000&amp;amp;lc1=4444CC&amp;amp;t=belmontechno-20&amp;amp;o=1&amp;amp;p=8&amp;amp;l=as1&amp;amp;m=amazon&amp;amp;f=ifr&amp;amp;md=10FE9736YVPPT7A0FBG2&amp;amp;asins=0981531601" style="width:120px;height:240px;"&gt;&lt;/iframe&gt;</td><td>&lt;iframe frameborder="0" marginheight="0" marginwidth="0" scrolling="no" src="http://rcm.amazon.com/e/cm?lt1=_blank&amp;amp;bc1=FFFFFF&amp;amp;IS2=1&amp;amp;npa=1&amp;amp;bg1=FFFFFF&amp;amp;fc1=000000&amp;amp;lc1=4444CC&amp;amp;t=belmontechno-20&amp;amp;o=1&amp;amp;p=8&amp;amp;l=as1&amp;amp;m=amazon&amp;amp;f=ifr&amp;amp;md=10FE9736YVPPT7A0FBG2&amp;amp;asins=0596007507" style="width:120px;height:240px;"&gt;&lt;/iframe&gt;</td></tr></tbody></table><br/><br/><p style="text-align: center; background-color: #666666; color: #FFFFFF;">From The Book Depository</p><br/><a href="http://www.bookdepository.co.uk/book/9781933988139/Walls/?a_aid=belmonttechnology" target="_blank">Spring in Action - Craig Walls &amp; Ryan Breidenbach (Manning)</a><br/><br/><a href="http://www.bookdepository.co.uk/book/9781932394153/Hibernate-in-Action/?a_aid=belmonttechnology" target="_blank">Hibernate in Action - Gavin King &amp; Christian Bauer (Manning)</a><br/><br/><a href="http://www.bookdepository.co.uk/book/9781590599792/Spring-Recipes/?a_aid=belmonttechnology" target="_blank">Spring Recipes - Gary Mak (Apress)</a><br/><br/><a href="http://www.bookdepository.co.uk/book/9780981531601/Programming-in-Scala/?a_aid=belmonttechnology" target="_blank">Programming in Scala - Martin Odersky, Lex Spoon &amp; Bill Venners (Artima)</a><br/><br/><a href="http://www.bookdepository.co.uk/book/9780596007508/Maven-a-Developers-Notebook/?a_aid=belmonttechnology" target="_blank">Maven - A Developer's Notebook - Vincent Massol &amp; Timothy M. O'Brien (O'Reilly)</a><br/><br/><br/><span style="font-size: 130%;"><span style="font-weight: bold;">Problems, Problems, Problems</span></span><br/><br/>Okay, in all honesty, it was nowhere near as straightforward to create this simple webapp as the journal above makes out. There were a number of compilation errors, thrice as many runtime exceptions, and the number of Google searches required was approaching a googol. But for your benefit - either by help or by humour - I've documented below the error, cause and solution to all of the hitches I encountered along the way.<br/><br/><span style="font-size: 130%;"><span style="font-weight: bold;">Problem 1: NoClassDefFound when running Scala App in IntelliJ</span></span><br/><br/>When I first tried to run the App class in IntelliJ, I got a <code>NoClassDefFoundError</code> as output.<br/>At this point, I opened the Maven tab and tried to run the 'test' phase, which told me that I didn't have a Maven Home Directory set, so I went into the project settings and fixed that.<br/>After this, I was able to run the 'test' phase successfully, and then the App class ran successfully, too.<br/><br/><span style="font-size: 130%;"><span style="font-weight: bold;">Problem 2: Invalid URI / Invalid Authority trying to access the Maven repository</span></span><br/><br/>After first adding Spring to the POM, I got some errors in my Maven pane in IDEA. I tried running the compile goal and got the following Maven error in the console:<br/><pre class="brush: text"><br/>Invalid uri 'http:// repository.springsource.com/maven/bundles/release/org/springframework/org.springframework.context/3.0.0.RELEASE/org.springframework.context-3.0.0.RELEASE.pom': Invalid authority<br/></pre>I copied and pasted this URL into Firefox, upon which it did a Google search, which is an unusual thing to do with a URL. Looking closer, I realised there was a space after http:// in the repository URL that I'd pasted into the POM. I deleted the space and was able to run the compile goal successfully (although, at this point, there was nothing to compile!)<br/><br/><br/><span style="font-size: 130%;"><span style="font-weight: bold;">Problem 3: Type Mismatch in Scala annotation</span></span><br/><br/>When I first created the <code>HelloWorldController</code> and tried to run the <code>mvn package</code> phase, I got the following compilation error:<br/><pre class="brush: text"><br/>[ERROR] /Users/graham/Code/scala-spring-hibernate/src/main/scala/au/com/belmonttechnology/spring/web/HelloWorldConroller.scala:16: error: type mismatch;<br/>[INFO]  found   : java.lang.String("/hello.html")<br/>[INFO]  required: Array[java.lang.String]<br/>[INFO]   @RequestMapping("/hello.html")<br/></pre><br/>It was easy enough to figure out how to fix this - in Scala, annotation parameters that are an array require <code>Array(…)</code> around them. In Java, you're allowed to leave the curly braces out when there's only one value for an array in an annotation, but Scala (at the moment) always requires an actual array.<br/><br/><b>References:</b><br/><a href="http://old.nabble.com/Re%3A-arrays-in-annotation-arguments-p19631280.html" target="_blank">Arrays in Scala annotation arguments</a><br/><br/><span style="font-size: 130%;"><span style="font-weight: bold;">Problem 4: IntelliJ IDEA not compiling Scala code</span></span><br/><br/>While I was fixing the problem with the annotation, I noticed a much more worrying problem, which was that IDEA wasn't compiling my Scala code. Pressing CTRL-F9 (Command-F9, actually) did nothing, even if I changed the code and saved the file and tried again.<br/><br/>Coincidentally, I also noticed at this point that controller was actually spelled 'Conroller'. So I renamed it, and just after I did a little box flashed up saying a Scala file had been detected and did I want to install the Scala facet. I wasn't quick enough to click it the first time, so I had to rename the controller again and hit the 'Create Scala facet' link.<br/><br/>Then I tried to compile again and I was shown a dialog box with the message "Cannot compile Scala files. Please attach a scala-compiler.jar to any project module." Seeing as I'm using Maven, I decided to add the Scala compiler dependency to the POM instead of directly into IntelliJ (which I assumed might remove it on the next POM update anyway):<br/><pre class="brush: xml"><br/>        &lt;dependency&gt;<br/>            &lt;groupId&gt;org.scala-lang&lt;/groupId&gt;<br/>            &lt;artifactId&gt;scala-compiler&lt;/artifactId&gt;<br/>            &lt;version&gt;${scala.version}&lt;/version&gt;<br/>            &lt;scope&gt;provided&lt;/scope&gt;<br/>        &lt;/dependency&gt;<br/></pre>I don't want to package the Scala compiler into my WAR, so I've used the 'provided' scope because this makes the artefacts available at compile time, but NOT at runtime. Now I compiled in IDEA, and finally I get the same error in IDEA that Maven was giving me earlier, and I fix the annotation on the controller to use an Array:<br/><pre class="brush: scala"><br/>  @RequestMapping(Array("/hello.html"))<br/></pre><br/><br/><br/><span style="font-size: 130%;"><span style="font-weight: bold;">Problem 5: AppTest.testKO fails (even though I deleted it)</span></span><br/><br/>After getting IDEA compiling Scala properly, I executed the Maven <code>package</code> goal again and that silly <code>AppTest.testKO</code> caused my build to fail, but I'd deleted the test class! I realised I hadn't run the 'clean' task for a while, so I did that and then it was all building successfully again.<br/><br/><span style="font-size: 130%;"><span style="font-weight: bold;">Problem 6: Spring Web requires Commons Logging</span></span><br/><br/>When I first tried to start Jetty, I got this error:<br/><pre class="brush: text"><br/>2010-01-16 13:59:12.392:WARN::FAILED ContextHandlerCollection@58a1a199: java.lang.NoClassDefFoundError: org/apache/commons/logging/LogFactory<br/>2010-01-16 13:59:12.392:WARN::FAILED HandlerCollection@5b787144: java.lang.NoClassDefFoundError: org/apache/commons/logging/LogFactory<br/>2010-01-16 13:59:12.392:WARN::Error starting handlers<br/>java.lang.NoClassDefFoundError: org/apache/commons/logging/LogFactory<br/> at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:179)<br/> at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:47)<br/></pre>It appears that spring-web requires commons-logging, but doesn't declare it as a dependancy. I solved it by adding this to the POM:<br/><pre class="brush: xml"><br/>&lt;dependency&gt;<br/>    &lt;groupId&gt;commons-logging&lt;/groupId&gt;<br/>    &lt;artifactId&gt;commons-logging&lt;/artifactId&gt;<br/>    &lt;version&gt;1.1.1&lt;/version&gt;<br/>&lt;/dependency&gt;<br/></pre><br/><span style="font-size: 130%;"><span style="font-weight: bold;">Problem 7: DispatcherServlet's Context Configuration File</span></span><br/><br/>Having fixed the commons-logging problem, I started Jetty again and got this error:<br/><pre class="brush: text"><br/>INFO: Loading XML bean definitions from ServletContext resource [/WEB-INF/dispatcher-servlet.xml]<br/>Jan 16, 2010 2:01:07 PM org.springframework.web.servlet.FrameworkServlet initServletBean<br/>SEVERE: Context initialization failed<br/>org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from ServletContext resource [/WEB-INF/dispatcher-servlet.xml]; nested exception is java.io.FileNotFoundException: Could not open ServletContext resource [/WEB-INF/dispatcher-servlet.xml]<br/> at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:341)<br/></pre>By default, the <code>DispatcherServlet</code> will look for a config file with the name of the servlet entry ('dispatcher', in my web.xml) with "-servlet.xml" tacked on the end. I got the DispatcherServlet to read my configuration file by adding this to the <code>&lt;servlet&gt;</code> in web.xml:<br/><pre class="brush: xml"><br/>        &lt;init-param&gt;<br/>            &lt;param-name&gt;contextConfigLocation&lt;/param-name&gt;<br/>            &lt;param-value&gt;/WEB-INF/web-context.xml&lt;/param-value&gt;<br/>        &lt;/init-param&gt;<br/></pre><br/><b>References:</b><br/><a href="http://static.springsource.org/spring/docs/3.0.x/api/org/springframework/web/servlet/FrameworkServlet.html" target="_blank">Spring FrameworkServlet javadoc</a><br/><br/><span style="font-size: 130%;"><span style="font-weight: bold;">Problem 8: Scala Syntax for Accessing a Class object at Runtime</span></span><br/><br/>When I first wrote the <code>CustomerController.viewCustomer</code> method, I tried to use the Java syntax to access the Customer's corresponding (runtime) class object:<br/><pre class="brush: java"><br/>sessionFactory.get(Customer.class, customerId)<br/></pre>which didn't compile. After realising I'd never had to do this before in Scala, I went searching and found that the syntax for getting the class object representing a type at runtime in Scala is:<br/><pre class="brush: scala"><br/>classOf[Customer]<br/></pre><br/><b>References:</b><br/><a href="http://stackoverflow.com/questions/1135248/scala-equivalent-of-java-java-lang-classt-object" target="_blank">Scala for accessing a Class at runtime</a><br/><br/><br/><span style="font-size: 130%;"><span style="font-weight: bold;">Problem 9: Hibernate Depends on the javax.transaction / JTA</span></span><br/><br/>When I first added Hibernate to the POM, I tried to compile (without adding any Hibernate code) and Maven gave me the following error:<br/><pre class="brush: text"><br/>Missing:<br/>----------<br/>1) javax.transaction:jta:jar:1.0.1B<br/><br/>  Try downloading the file manually from: <br/>      http://java.sun.com/products/jta<br/></pre>Since I was pretty sure that wouldn't be using any JTA features, I simply added an exclusion for it to the &lt;dependency&gt; in the POM:<br/><pre class="brush: xml"><br/>        &lt;dependency&gt;<br/>            &lt;groupId&gt;org.hibernate&lt;/groupId&gt;<br/>            &lt;artifactId&gt;hibernate&lt;/artifactId&gt;<br/>            &lt;version&gt;3.2.7.ga&lt;/version&gt;<br/>            &lt;exclusions&gt;<br/>                &lt;exclusion&gt;<br/>                    &lt;groupId&gt;javax.transaction&lt;/groupId&gt;<br/>                    &lt;artifactId&gt;jta&lt;/artifactId&gt;<br/>                &lt;/exclusion&gt;<br/>            &lt;/exclusions&gt;<br/>        &lt;/dependency&gt;<br/></pre><br/>I should mention that IntelliJ's POM integration here was AWESOME, allowing me to auto-complete the group and artefact IDs of the exclusion by showing me a list of all Hibernate's transitive dependencies! If any IDEA developers are reading this - you guys ROCK!<br/><br/><span style="font-size: 130%;"><span style="font-weight: bold;">Problem 10: Spring can't find HttpServletRequest</span></span><br/><br/>When I tried to compile the <code>CustomerController</code> for the first time, I received this compilation error:<br/><pre class="brush: text"><br/>Error: error while loading View, Missing dependency 'class javax.servlet.http.HttpServletRequest', required by /Users/graham/.m2/repository/org/springframework/org.springframework.web.servlet/3.0.0.RELEASE/org.springframework.web.servlet-3.0.0.RELEASE.jar(org/springframework/web/servlet/View.class)<br/></pre>The problem this time was that spring-web, while relying heavily on the Servlet API, declares the dependency with the 'provided' scope, which is the right thing for the Spring guys to do but a small gotcha for people trying to use it. The solution is just to add a sevlet-api dependency into your own POM (which should ALSO use the 'provided' scope):<br/><pre class="brush: xml"><br/>&lt;dependency&gt;<br/>    &lt;groupId&gt;javax.servlet&lt;/groupId&gt;<br/>    &lt;artifactId&gt;servlet-api&lt;/artifactId&gt;<br/>    &lt;version&gt;2.5&lt;/version&gt;<br/>     &lt;scope&gt;provided&lt;/scope&gt;<br/>&lt;/dependency&gt;<br/></pre><br/><b>References:</b><br/><a href="http://mvnrepository.com/artifact/javax.servlet/servlet-api/2.5" target="_blank">Maven Repository: javax.servlet::servlet-api</a><br/><br/><br/><span style="font-size: 130%;"><span style="font-weight: bold;">Problem 11: Incompatible version of SLF4J</span></span><br/><br/>After adding the javax.servlet dependency, I started up Jetty again and Spring spewed out the following error along with a massive stack trace:<br/><pre class="brush: text"><br/>2010-01-16 21:47:54.804:WARN::Nested in org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in ServletContext resource [/WEB-INF/spring-context.xml]: Invocation of init method failed; nested exception is java.lang.IllegalAccessError: tried to access field org.slf4j.impl.StaticLoggerBinder.SINGLETON from class org.slf4j.LoggerFactory:<br/>java.lang.IllegalAccessError: tried to access field org.slf4j.impl.StaticLoggerBinder.SINGLETON from class org.slf4j.LoggerFactory<br/></pre>I found a forum saying that the slf4j-api distribution had a different implementation of StaticLoggerBinder to the one in the slf4j implementation JARs, and that to get it to work you need to include both in your classpath (with the API having priority). The solution was to add the SLF4J API to the POM:<br/><pre class="brush: xml"><br/>        &lt;dependency&gt;<br/>            &lt;groupId&gt;org.slf4j&lt;/groupId&gt;<br/>            &lt;artifactId&gt;slf4j-api&lt;/artifactId&gt;<br/>            &lt;version&gt;1.5.8&lt;/version&gt;<br/>        &lt;/dependency&gt;<br/>        &lt;dependency&gt;<br/>            &lt;groupId&gt;org.slf4j&lt;/groupId&gt;<br/>            &lt;artifactId&gt;slf4j-jdk14&lt;/artifactId&gt;<br/>            &lt;version&gt;1.5.8&lt;/version&gt;<br/>        &lt;/dependency&gt;<br/></pre><br/><b>References:</b><br/><a href="https://forum.hibernate.org/viewtopic.php?p=2400801" target="_blank">StaticLoggerBinder.SINGLETON IllegalAccessError on Hibernate forum</a><br/><br/><span style="font-size: 130%;"><span style="font-weight: bold;">Problem 12: NoSuchMethodError in Hibernate Annotations</span></span><br/><br/>I was originally using Hibernate version 3.1.3, as there was some repository indexing page I had browsed suggested that was the latest. When I started up Jetty, I got this error message:<br/><pre class="brush: text"><br/>2010-01-16 21:52:06.913:WARN::Nested in org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in ServletContext resource [/WEB-INF/spring-context.xml]: Invocation of init method failed; nested exception is java.lang.NoSuchMethodError: org.hibernate.cfg.SecondPass.doSecondPass(Ljava/util/Map;)V:<br/>java.lang.NoSuchMethodError: org.hibernate.cfg.SecondPass.doSecondPass(Ljava/util/Map;)V<br/></pre><br/>I found a page where someone had the same problem and a respondent suggested they try a newer version of Hibernate, so I used IntelliJ's Maven integration to download the whole index of repo1.maven.org and then auto-complete the version for the Hibernate dependency, which showed me that the newest version of hibernate-annotaions was actually 3.4.0.ga. Switching to the latest version made the error go away.<br/><br/><br/><span style="font-size: 130%;"><span style="font-weight: bold;">Problem 13: Spring Form Binding Requires a Command object</span></span><br/><br/>When I first tried to view the newCustomer JSP, Jetty returned an error page showing this:<br/><pre class="brush: text"><br/>2010-01-16 21:54:19.068:WARN::/customers/new.html<br/>java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'command' available as request attribute<br/></pre>I had, as I often do, forgotten to provide a blank form object for the new form, which was easily solved by adding this method to the <code>CustomerController</code>:<br/><pre class="brush: scala"><br/>  @ModelAttribute("command")<br/>  def createCustomerForFormBinding = new Customer<br/></pre><br/><span style="font-size: 130%;"><span style="font-weight: bold;">Problem 14: Can't Access a Scala 'var' from JSP</span></span><br/><br/>After providing the blank form object for the JSP to bind from, I got this error:<br/><pre class="brush: text"><br/>Invalid property 'name' of bean class [au.com.belmonttechnology.data.Customer]: Bean property 'name' is not readable or has an invalid getter method: Does the return type of the getter match the parameter type of the setter?<br/></pre><br/>I was actually expecting this one to happen! It occurred because a var in a Scala object, while publicly accessible, does not conform to the JavaBeans specification, which is what JSPs and JSTL use to inspect beans and retrieve data from them. Scala provides the <code>@BeanProperty</code> annotation that can be used to tell the compiler to generate getter and setter methods for a variable in order to make it accessible by JavaBeans-reliant tools.<br/><pre class="brush: scala"><br/>  @BeanProperty<br/>  var name: String = null;<br/></pre><br/><b>References:</b><br/><a href="http://programming-scala.labs.oreilly.com/ch14.html#JavaBeanProperties" target="_blank">JavaBean Properties in Scala</a><br/><br/><br/><span style="font-size: 130%;"><span style="font-weight: bold;">Problem 15:</span></span><br/><br/>When I first submitted a request to <code>CustomerController.createNewCustomer</code>, I got the following error:<br/><pre class="brush: text"><br/>No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here<br/></pre>I remembered that I had decided to experiment and see whether my <code>OpenSessionInViewInterceptor</code> would be automagically picked up by the default annotation handler mappings (some Spring beans do this for some of their dependenices). But, they weren't. Solution: define the mappings bean explicitly and inject the interceptor as a property:<br/><pre class="brush: xml"><br/>    &lt;bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping"&gt;<br/>        &lt;property name="interceptors"&gt;<br/>            &lt;list&gt;&lt;ref bean="openSessionInViewInterceptor"/&gt;&lt;/list&gt;<br/>        &lt;/property&gt;<br/>    &lt;/bean&gt;<br/></pre><br/><br/>Problems solved.<br/>Hope you enjoyed that.<br/><br/>Graham.<div class="blogger-post-footer"><img alt="" height="1" src="https://blogger.googleusercontent.com/tracker/7317245822288637185-2558806089115520923?l=grahamhackingscala.blogspot.com" width="1"/></div>
<p><a href="http://feedads.g.doubleclick.net/~a/YpVG0J47IEk-IHUOhwjhSHKmFH4/0/da"><img border="0" ismap="true" src="http://feedads.g.doubleclick.net/~a/YpVG0J47IEk-IHUOhwjhSHKmFH4/0/di"/></a><br/>
<a href="http://feedads.g.doubleclick.net/~a/YpVG0J47IEk-IHUOhwjhSHKmFH4/1/da"><img border="0" ismap="true" src="http://feedads.g.doubleclick.net/~a/YpVG0J47IEk-IHUOhwjhSHKmFH4/1/di"/></a></p><img height="1" src="http://feeds.feedburner.com/~r/blogspot/vnby/~4/Ey9wylQB4Jo" width="1"/></div>
    </content>
    <updated>2010-09-04T04:34:25Z</updated>
    <published>2010-01-18T11:00:00Z</published>
    <category scheme="http://www.blogger.com/atom/ns#" term="intellij"/>
    <category scheme="http://www.blogger.com/atom/ns#" term="java"/>
    <category scheme="http://www.blogger.com/atom/ns#" term="REST"/>
    <category scheme="http://www.blogger.com/atom/ns#" term="create"/>
    <category scheme="http://www.blogger.com/atom/ns#" term="jsp"/>
    <category scheme="http://www.blogger.com/atom/ns#" term="mvc"/>
    <category scheme="http://www.blogger.com/atom/ns#" term="spring"/>
    <category scheme="http://www.blogger.com/atom/ns#" term="graham"/>
    <category scheme="http://www.blogger.com/atom/ns#" term="webapp"/>
    <category scheme="http://www.blogger.com/atom/ns#" term="maven"/>
    <category scheme="http://www.blogger.com/atom/ns#" term="web application"/>
    <category scheme="http://www.blogger.com/atom/ns#" term="hibernate"/>
    <category scheme="http://www.blogger.com/atom/ns#" term="introduction"/>
    <category scheme="http://www.blogger.com/atom/ns#" term="idea"/>
    <category scheme="http://www.blogger.com/atom/ns#" term="hsqldb"/>
    <category scheme="http://www.blogger.com/atom/ns#" term="tutorial"/>
    <category scheme="http://www.blogger.com/atom/ns#" term="how-to"/>
    <category scheme="http://www.blogger.com/atom/ns#" term="hacking"/>
    <category scheme="http://www.blogger.com/atom/ns#" term="scala"/>
    <category scheme="http://www.blogger.com/atom/ns#" term="annotations"/><feedburner:origLink xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0">http://grahamhackingscala.blogspot.com/2010/01/scala-spring-hibernate-maven-webapp-how.html</feedburner:origLink>
    <author>
      <name>Grazer</name>
      <email>noreply@blogger.com</email>
      <uri>http://www.blogger.com/profile/00435359638152521056</uri>
    </author>
    <source>
      <id>tag:blogger.com,1999:blog-7317245822288637185</id>
      <author>
        <name>Grazer</name>
        <email>noreply@blogger.com</email>
        <uri>http://www.blogger.com/profile/00435359638152521056</uri>
      </author>
      <link href="http://grahamhackingscala.blogspot.com/feeds/posts/default" rel="http://schemas.google.com/g/2005#feed" type="application/atom+xml"/>
      <link href="http://grahamhackingscala.blogspot.com/" rel="alternate" type="text/html"/>
      <link href="http://feeds.feedburner.com/blogspot/vnby" rel="self" type="application/atom+xml"/>
      <link href="http://pubsubhubbub.appspot.com/" rel="hub" type="text/html"/>
      <subtitle>The point of "Graham Hacking Scala" is to share with you my knowledge of and experience with the Scala programming language. The blog will contain everything from introductions to basic features through to in-depth analysis of complex techniques and problems. When I make mistakes, you will learn from my mistakes. When I discover cool features, you will learn about them, too.</subtitle>
      <title>Graham Hacking Scala</title>
      <updated>2010-09-04T16:58:00Z</updated>
    </source>
  </entry>

  <entry>
    <id>http://code.technically.us/post/1059041247</id>
    <link href="http://code.technically.us/post/1059041247" rel="alternate" type="text/html"/>
    <title>1366 x 768 MeeGo tablet coming to Germany in two weeks</title>
    <summary type="xhtml"><div xmlns="http://www.w3.org/1999/xhtml">&lt;object height="254" width="400"&gt;&lt;param name="movie" value="http://www.youtube.com/v/7EdNBTwHxWk&amp;amp;rel=0&amp;amp;egm=0&amp;amp;showinfo=0&amp;amp;fs=1"&gt;&lt;param name="wmode" value="transparent"&gt;&lt;param name="allowFullScreen" value="true"&gt;&lt;embed allowfullscreen="true" height="254" src="http://www.youtube.com/v/7EdNBTwHxWk&amp;amp;rel=0&amp;amp;egm=0&amp;amp;showinfo=0&amp;amp;fs=1" type="application/x-shockwave-flash" width="400" wmode="transparent"&gt;&lt;/embed&gt;&lt;/object&gt;<br/><br/><p><a href="http://www.blogeee.net/2010/09/wetab-une-tablette-11-6-sous-meego-qui-se-demarque/?utm_source=feedburner&amp;utm_medium=feed&amp;utm_campaign=Feed%3A+blogeee%2Farticles+%28Blogeee.net%29">1366 x 768 <em>MeeGo</em> tablet coming to Germany in two weeks</a></p></div>
    </summary>
    <updated>2010-09-03T16:17:00Z</updated>
    <category term="Good Resolutions"/>
    <category term="Linux"/>
    <category term="Not Android"/>
    <category term="Tablets"/>
    <category term="Video"/>
    <category term="MeeGo"/>
    <source>
      <id>http://code.technically.us/</id>
      <author>
        <name>Coderspiel</name>
      </author>
      <link href="http://tumblr.superfeedr.com/" rel="hub" type="text/html"/>
      <link href="http://code.technically.us/" rel="alternate" type="text/html"/>
      <link href="http://code.technically.us/rss" rel="self" type="application/rss+xml"/>
      <title>Coderspiel</title>
      <updated>2010-09-09T03:00:39Z</updated>
    </source>
  </entry>

  <entry>
    <id>http://code.technically.us/post/1058315201</id>
    <link href="http://code.technically.us/post/1058315201" rel="alternate" type="text/html"/>
    <title>SPDE Menger Sierpinski Ball</title>
    <summary type="xhtml"><div xmlns="http://www.w3.org/1999/xhtml">&lt;object height="325" width="400"&gt;&lt;param name="movie" value="http://www.youtube.com/v/Fl-V7GRAJJ4&amp;amp;rel=0&amp;amp;egm=0&amp;amp;showinfo=0&amp;amp;fs=1"&gt;&lt;param name="wmode" value="transparent"&gt;&lt;param name="allowFullScreen" value="true"&gt;&lt;embed allowfullscreen="true" height="325" src="http://www.youtube.com/v/Fl-V7GRAJJ4&amp;amp;rel=0&amp;amp;egm=0&amp;amp;showinfo=0&amp;amp;fs=1" type="application/x-shockwave-flash" width="400" wmode="transparent"&gt;&lt;/embed&gt;&lt;/object&gt;<br/><br/><p><a href="http://www.youtube.com/watch?v=Fl-V7GRAJJ4&amp;feature=youtu.be">SPDE Menger Sierpinski Ball</a></p></div>
    </summary>
    <updated>2010-09-03T13:04:42Z</updated>
    <category term="Scala"/>
    <category term="Processing"/>
    <category term="Spde"/>
    <category term="Sierpinski"/>
    <source>
      <id>http://code.technically.us/</id>
      <author>
        <name>Coderspiel</name>
      </author>
      <link href="http://tumblr.superfeedr.com/" rel="hub" type="text/html"/>
      <link href="http://code.technically.us/" rel="alternate" type="text/html"/>
      <link href="http://code.technically.us/rss" rel="self" type="application/rss+xml"/>
      <title>Coderspiel</title>
      <updated>2010-09-09T03:00:39Z</updated>
    </source>
  </entry>

  <entry>
    <id>tag:blogger.com,1999:blog-5453594210552123250.post-8931739648059375004</id>
    <link href="http://heikoseeberger.blogspot.com/feeds/8931739648059375004/comments/default" rel="replies" type="application/atom+xml"/>
    <link href="https://www.blogger.com/comment.g?blogID=5453594210552123250&amp;postID=8931739648059375004" rel="replies" type="text/html"/>
    <link href="http://www.blogger.com/feeds/5453594210552123250/posts/default/8931739648059375004" rel="edit" type="application/atom+xml"/>
    <link href="http://www.blogger.com/feeds/5453594210552123250/posts/default/8931739648059375004" rel="self" type="application/atom+xml"/>
    <link href="http://heikoseeberger.blogspot.com/2010/09/slf4s-logging-scala-way.html" rel="alternate" type="text/html"/>
    <title>SLF4S - Logging the Scala way</title>
    <content type="xhtml"><div xmlns="http://www.w3.org/1999/xhtml">Do we need another logging framework in the Java/Scala world? Certainly not! As Scala is fully "downward" compatible to Java, we can use whatever Java logging solution we want. And there are many, aren't there?.<br/><br/>So why <a href="http://github.com/weiglewilczek/slf4s">SLF4S</a>? Well, SLF4S isn't another logging framework, but a very thin Scala wrapper around SLF4J which has emerged as the leading Java logging solution. Why do we need a Scala wrapper for SLF4S? Well, there are some nice Scala features that can make logging even easier and/or more performant.<br/><br/>First, SLF4J <span style="font-style: italic;">Logger</span>s use by-name parameters which are only evaluated if needed/accessed. When logging "traditionally", we often create messages by concatenating Strings or using the <span style="font-style: italic;">String.format</span> method, even if we don't need these messages in the end because the logging level is not enabled. Of course we could "manually" check whether the logging level is enabled, e.g. by calling <span style="font-style: italic;">logger.isDebugEnabled</span>, but we often don't, because it's cumbersome. With by-name parameters we can simply call our log methods and let SLF4S check whether the log level is enabled. Just take a look at one example:<br/><pre>def debug(msg: =&gt; String) {<br/> if (slf4jLogger.isDebugEnabled) slf4jLogger debug msg<br/>}</pre><br/>Second, SLF4S offers a <span style="font-style: italic;">Logging</span> trait which can be mixed into any class to make a <span style="font-style: italic;">Logger</span> instance available. That particular <span style="font-style: italic;">Logger</span> will be initialized with the name of the class it is mixed into which is a common use case.<br/><pre>class MyClazz extends SomeClazz with Logging<br/>  ...<br/>  logger debug "SLF4S just rocks!"<br/>  ...</pre><br/>Of course you can create <span style="font-style: italic;">Logger</span>s with arbitrary names by calling <span style="font-style: italic;">Logger("SomeSpecialName")</span>.<br/><br/>Last but not least, SLF4S offers implicit conversions from "usual" SLF4J <span style="font-style: italic;">Logger</span>s into "pimped" SLF4S <span style="font-style: italic;">Logger</span>s.<br/><br/>Ah, and of course, SLF4S is <a href="http://www.osgi.org">OSGi</a> compliant. But that's not a big surprise, taking into account that the authors are OSGi fanboys and SLF4J is OSGi compliant, too.<div class="blogger-post-footer"><img alt="" height="1" src="https://blogger.googleusercontent.com/tracker/5453594210552123250-8931739648059375004?l=heikoseeberger.blogspot.com" width="1"/></div></div>
    </content>
    <updated>2010-09-03T08:06:41Z</updated>
    <published>2010-09-02T17:54:00Z</published>
    <category scheme="http://www.blogger.com/atom/ns#" term="scala"/>
    <author>
      <name>Heiko Seeberger</name>
      <email>noreply@blogger.com</email>
      <uri>http://www.blogger.com/profile/05107839410251890061</uri>
    </author>
    <source>
      <id>tag:blogger.com,1999:blog-5453594210552123250</id>
      <author>
        <name>Heiko Seeberger</name>
        <email>noreply@blogger.com</email>
        <uri>http://www.blogger.com/profile/05107839410251890061</uri>
      </author>
      <link href="http://heikoseeberger.blogspot.com/feeds/posts/default" rel="http://schemas.google.com/g/2005#feed" type="application/atom+xml"/>
      <link href="http://www.blogger.com/feeds/5453594210552123250/posts/default/-/scala" rel="self" type="application/atom+xml"/>
      <link href="http://heikoseeberger.blogspot.com/search/label/scala" rel="alternate" type="text/html"/>
      <link href="http://pubsubhubbub.appspot.com/" rel="hub" type="text/html"/>
      <subtitle>Welcome to my blog!</subtitle>
      <title>Heiko Seeberger</title>
      <updated>2010-09-04T11:04:09Z</updated>
    </source>
  </entry>

  <entry>
    <id>tag:blogger.com,1999:blog-22587889.post-6180939564075434164</id>
    <link href="http://debasishg.blogspot.com/feeds/6180939564075434164/comments/default" rel="replies" type="application/atom+xml"/>
    <link href="https://www.blogger.com/comment.g?blogID=22587889&amp;postID=6180939564075434164" rel="replies" type="text/html"/>
    <link href="http://www.blogger.com/feeds/22587889/posts/default/6180939564075434164" rel="edit" type="application/atom+xml"/>
    <link href="http://debasishg.blogspot.com/feeds/posts/default/6180939564075434164" rel="self" type="application/atom+xml"/>
    <link href="http://debasishg.blogspot.com/2010/09/towards-generic-apis-for-open-world.html" rel="alternate" type="text/html"/>
    <title>Towards generic APIs for the open world</title>
    <content type="xhtml"><div xmlns="http://www.w3.org/1999/xhtml"><span class="Apple-style-span" style="font-family: Arial; font-size: small;"/><br/><span class="Apple-style-span" style="font-family: Arial; font-size: small;"><span class="Apple-style-span" style="font-size: 13px;">In my <a href="http://debasishg.blogspot.com/2010/08/random-thoughts-on-clojure-protocols.html">last post</a> on how Clojure protocols encourage open abstractions, I did some quick rounds between type classes in Haskell and protocols in Clojure. At the end in the section titled "Not really a type class", I mentioned about the <code>read</code> function of Haskell's <code>Read</code> type class. <code>read</code> takes a <code>String</code> and returns a type - hence it doesn't dispatch on the function argument, but rather on the return type. Clojure protocols can't do this, I am not aware of any dynamic language that can do this. Check out James Iry's <a href="http://debasishg.blogspot.com/2010/08/random-thoughts-on-clojure-protocols.html?showComment=1282928486610#c616188610926898843">insightful comment</a> on this subject on the post.</span><br/><span class="Apple-style-span" style="font-size: small;"><span class="Apple-style-span" style="font-size: 13px;"><br/></span></span><br/><span class="Apple-style-span" style="font-size: small;"><span class="Apple-style-span" style="font-size: 13px;">With type classes <i>all dispatch is static</i> - the dispatch map is passed as a dictionary of types and inferred by the compiler. What benefit does this bring on to us ? Do we really get anything special when the language supports APIs like the <code>read</code> method of Haskell's <code>Read</code> type class ?</span></span><br/><span class="Apple-style-span" style="font-size: small;"><span class="Apple-style-span" style="font-size: 13px;"><br/></span></span><br/><span class="Apple-style-span" style="font-size: small;"><span class="Apple-style-span" style="font-size: 13px;">In this post I try to explore how type classes help design generic APIs that are <i>open</i> and can work seamlessly with abstractions that you implement much later in timeline than the type class itself. This is in contrast to subtype polymorphism where all subtypes are bound by the contracts that the super type exposes. In this sense subtype polymorphism is <i>closed</i>.</span></span><br/><span class="Apple-style-span" style="font-size: small;"><span class="Apple-style-span" style="font-size: 13px;"><br/></span></span><br/><span class="Apple-style-span" style="font-size: small;"><span class="Apple-style-span" style="font-size: 13px;">This post is inspired in part by the excellent article <a href="http://blog.ezyang.com/2010/08/generalizing-apis/">Generalizing APIs</a> by Edward Z. Yang. For this post I will use Scala, my current language of choice for most of the things I do today.</span></span><br/><span class="Apple-style-span" style="font-size: small;"><span class="Apple-style-span" style="font-size: 13px;"><br/></span></span><br/><span class="Apple-style-span" style="font-size: small;"><span class="Apple-style-span" style="font-size: 13px;"><b>My generic API</b></span></span><br/><span class="Apple-style-span" style="font-size: small;"><span class="Apple-style-span" style="font-size: 13px;"><br/></span></span><br/><span class="Apple-style-span" style="font-size: 13px;">I want to implement a <code>read</code> API like the one in Haskell encoded in a Scala type class .. Let's make it generic in the type that it returns ..</span><br/><span class="Apple-style-span" style="font-size: small;"><span class="Apple-style-span" style="font-size: 13px;"><br/></span></span><br/><span class="Apple-style-span" style="font-size: small;"><span class="Apple-style-span" style="font-size: 13px;"><code><span class="java_comment">// type class</span></code></span><code/></span><code/><br/><code><span class="Apple-style-span" style="font-size: small;"><span class="Apple-style-span" style="font-size: 13px;"><span class="java_comment">// reads a string, returns a T</span></span></span><br/><span class="Apple-style-span" style="font-size: small;"><span class="Apple-style-span" style="font-size: 13px;"><span class="java_keyword">trait</span><span class="java_plain"> </span><span class="java_type">Read</span><span class="java_separator">[</span><span class="java_plain">T</span><span class="java_separator">]</span><span class="java_plain"> </span><span class="java_separator">{</span><span class="java_plain"/></span></span><br/><span class="Apple-style-span" style="font-size: small;"><span class="Apple-style-span" style="font-size: 13px;"><span class="java_plain">  </span><span class="java_keyword">def</span><span class="java_plain"> read</span><span class="java_separator">(</span><span class="java_plain">s</span><span class="java_operator">:</span><span class="java_plain"> </span><span class="java_type">String</span><span class="java_separator">)</span><span class="java_operator">:</span><span class="java_plain"> T</span></span></span><br/><span class="Apple-style-span" style="font-size: small;"><span class="Apple-style-span" style="font-size: 13px;"><span class="java_separator">}</span><span class="java_plain"/></span></span><br/><span class="Apple-style-span" style="font-size: small;"><span class="Apple-style-span" style="font-size: 13px;"><span class="java_plain"/></span></span></code><code><span class="Apple-style-span" style="font-size: small;"><span class="Apple-style-span" style="font-size: 13px;"/></span></code><span class="Apple-style-span" style="font-size: small;"/><br/><span class="Apple-style-span" style="font-size: small;"><span class="Apple-style-span" style="font-size: 13px;"><b>For the open world</b></span></span><br/><span class="Apple-style-span" style="font-size: small;"><span class="Apple-style-span" style="font-size: 13px;"><br/></span></span><br/><span class="Apple-style-span" style="font-size: small;"><span class="Apple-style-span" style="font-size: 13px;">We can define instances of this type class by instantiating the trait as objects. Type classes are implemented in Scala using implicits. In case you're not familiar with the concept, here's what I <a href="http://debasishg.blogspot.com/2010/06/scala-implicits-type-classes-here-i.html">wrote</a> about them some time back.</span></span><br/><span class="Apple-style-span" style="font-size: small;"><span class="Apple-style-span" style="font-size: 13px;"><br/></span></span><br/><span class="Apple-style-span" style="font-size: small;"><span class="Apple-style-span" style="font-size: 13px;"><code><span class="java_comment">// instance for Int</span></code></span><code/></span><code/><br/><code><span class="Apple-style-span" style="font-size: small;"><span class="Apple-style-span" style="font-size: 13px;"><span class="java_keyword">implicit</span><span class="java_plain"> </span><span class="java_keyword">object</span><span class="java_plain"> </span><span class="java_type">IntRead</span><span class="java_plain"> </span><span class="java_keyword">extends</span><span class="java_plain"> </span><span class="java_type">Read</span><span class="java_separator">[</span><span class="java_type">Int</span><span class="java_separator">]</span><span class="java_plain"> </span><span class="java_separator">{</span><span class="java_plain"/></span></span><br/><span class="Apple-style-span" style="font-size: small;"><span class="Apple-style-span" style="font-size: 13px;"><span class="java_plain">  </span><span class="java_keyword">def</span><span class="java_plain"> read</span><span class="java_separator">(</span><span class="java_plain">s</span><span class="java_operator">:</span><span class="java_plain"> </span><span class="java_type">String</span><span class="java_separator">)</span><span class="java_plain"> </span><span class="java_operator">=</span><span class="java_plain"> s</span><span class="java_separator">.</span><span class="java_plain">toInt</span></span></span><br/><span class="Apple-style-span" style="font-size: small;"><span class="Apple-style-span" style="font-size: 13px;"><span class="java_separator">}</span><span class="java_plain"/></span></span><br/><span class="Apple-style-span" style="font-size: small;"><span class="Apple-style-span" style="font-size: 13px;"><span class="java_plain"/></span></span><br/><span class="Apple-style-span" style="font-size: small;"><span class="Apple-style-span" style="font-size: 13px;"><span class="java_comment">// instance for Float</span></span></span><br/><span class="Apple-style-span" style="font-size: small;"><span class="Apple-style-span" style="font-size: 13px;"><span class="java_keyword">implicit</span><span class="java_plain"> </span><span class="java_keyword">object</span><span class="java_plain"> </span><span class="java_type">FloatRead</span><span class="java_plain"> </span><span class="java_keyword">extends</span><span class="java_plain"> </span><span class="java_type">Read</span><span class="java_separator">[</span><span class="java_type">Float</span><span class="java_separator">]</span><span class="java_plain"> </span><span class="java_separator">{</span><span class="java_plain"/></span></span><br/><span class="Apple-style-span" style="font-size: small;"><span class="Apple-style-span" style="font-size: 13px;"><span class="java_plain">  </span><span class="java_keyword">def</span><span class="java_plain"> read</span><span class="java_separator">(</span><span class="java_plain">s</span><span class="java_operator">:</span><span class="java_plain"> </span><span class="java_type">String</span><span class="java_separator">)</span><span class="java_plain"> </span><span class="java_operator">=</span><span class="java_plain"> s</span><span class="java_separator">.</span><span class="java_plain">toFloat</span></span></span><br/><span class="Apple-style-span" style="font-size: small;"><span class="Apple-style-span" style="font-size: 13px;"><span class="java_separator">}</span><span class="java_plain"/></span></span><br/><span class="Apple-style-span" style="font-size: small;"><span class="Apple-style-span" style="font-size: 13px;"><span class="java_plain"/></span></span></code><code><span class="Apple-style-span" style="font-size: small;"><span class="Apple-style-span" style="font-size: 13px;"/></span></code><span class="Apple-style-span" style="font-size: small;"/><br/><span class="Apple-style-span" style="font-size: small;"><span class="Apple-style-span" style="font-size: 13px;">These are very much like what you would do with type class instances in Haskell. You can even create instances for your own abstractions ..</span></span><br/><span class="Apple-style-span" style="font-size: small;"><span class="Apple-style-span" style="font-size: 13px;"><br/></span></span><br/><span class="Apple-style-span" style="font-size: small;"><span class="Apple-style-span" style="font-size: 13px;"><code><span class="java_keyword">case</span><span class="java_plain"> </span><span class="java_keyword">class</span><span class="java_plain"> </span><span class="java_type">Name</span><span class="java_separator">(</span><span class="java_plain">last</span><span class="java_operator">:</span><span class="java_plain"> </span><span class="java_type">String</span><span class="java_separator">,</span><span class="java_plain"> first</span><span class="java_operator">:</span><span class="java_plain"> </span><span class="java_type">String</span><span class="java_separator">)</span><span class="java_plain"/></code></span><code/></span><code/><br/><code><span class="Apple-style-span" style="font-size: small;"><span class="Apple-style-span" style="font-size: 13px;"><span class="java_plain"/></span></span><br/><span class="Apple-style-span" style="font-size: small;"><span class="Apple-style-span" style="font-size: 13px;"><span class="java_keyword">object</span><span class="java_plain"> </span><span class="java_type">NameDescription</span><span class="java_plain"> </span><span class="java_separator">{</span><span class="java_plain"/></span></span><br/><span class="Apple-style-span" style="font-size: small;"><span class="Apple-style-span" style="font-size: 13px;"><span class="java_plain">  </span><span class="java_keyword">def</span><span class="java_plain"> unapply</span><span class="java_separator">(</span><span class="java_plain">s</span><span class="java_operator">:</span><span class="java_plain"> </span><span class="java_type">String</span><span class="java_separator">)</span><span class="java_operator">:</span><span class="java_plain"> </span><span class="java_type">Option</span><span class="java_separator">[(</span><span class="java_type">String</span><span class="java_separator">,</span><span class="java_plain"> </span><span class="java_type">String</span><span class="java_separator">)]</span><span class="java_plain"> </span><span class="java_operator">=</span><span class="java_plain"> </span><span class="java_separator">{</span><span class="java_plain"/></span></span><br/><span class="Apple-style-span" style="font-size: small;"><span class="Apple-style-span" style="font-size: 13px;"><span class="java_plain">    </span><span class="java_keyword">val</span><span class="java_plain"> a </span><span class="java_operator">=</span><span class="java_plain"> s</span><span class="java_separator">.</span><span class="java_plain">split</span><span class="java_separator">(</span><span class="java_literal">"/"</span><span class="java_separator">)</span><span class="java_plain"/></span></span><br/><span class="Apple-style-span" style="font-size: small;"><span class="Apple-style-span" style="font-size: 13px;"><span class="java_plain">    </span><span class="java_type">Some</span><span class="java_separator">((</span><span class="java_plain">a</span><span class="java_separator">(</span><span class="java_literal">1</span><span class="java_separator">),</span><span class="java_plain"> a</span><span class="java_separator">(</span><span class="java_literal">0</span><span class="java_separator">)))</span><span class="java_plain"/></span></span><br/><span class="Apple-style-span" style="font-size: small;"><span class="Apple-style-span" style="font-size: 13px;"><span class="java_plain">  </span><span class="java_separator">}</span><span class="java_plain"/></span></span><br/><span class="Apple-style-span" style="font-size: small;"><span class="Apple-style-span" style="font-size: 13px;"><span class="java_separator">}</span><span class="java_plain"/></span></span><br/><span class="Apple-style-span" style="font-size: small;"><span class="Apple-style-span" style="font-size: 13px;"><span class="java_plain"/></span></span><br/><span class="Apple-style-span" style="font-size: small;"><span class="Apple-style-span" style="font-size: 13px;"><span class="java_comment">// instance for Name</span></span></span><br/><span class="Apple-style-span" style="font-size: small;"><span class="Apple-style-span" style="font-size: 13px;"><span class="java_keyword">import</span><span class="java_plain"> </span><span class="java_type">NameDescription</span><span class="java_separator">.</span><span class="java_plain">_</span></span></span><br/><span class="Apple-style-span" style="font-size: small;"><span class="Apple-style-span" style="font-size: 13px;"><span class="java_keyword">implicit</span><span class="java_plain"> </span><span class="java_keyword">object</span><span class="java_plain"> </span><span class="java_type">NameRead</span><span class="java_plain"> </span><span class="java_keyword">extends</span><span class="java_plain"> </span><span class="java_type">Read</span><span class="java_separator">[</span><span class="java_type">Name</span><span class="java_separator">]</span><span class="java_plain"> </span><span class="java_separator">{</span><span class="java_plain"/></span></span><br/><span class="Apple-style-span" style="font-size: small;"><span class="Apple-style-span" style="font-size: 13px;"><span class="java_plain">  </span><span class="java_keyword">def</span><span class="java_plain"> read</span><span class="java_separator">(</span><span class="java_plain">s</span><span class="java_operator">:</span><span class="java_plain"> </span><span class="java_type">String</span><span class="java_separator">)</span><span class="java_plain"> </span><span class="java_operator">=</span><span class="java_plain"> s </span><span class="java_keyword">match</span><span class="java_plain"> </span><span class="java_separator">{</span><span class="java_plain">             </span></span></span><br/><span class="Apple-style-span" style="font-size: small;"><span class="Apple-style-span" style="font-size: 13px;"><span class="java_plain">    </span><span class="java_keyword">case</span><span class="java_plain"> </span><span class="java_type">NameDescription</span><span class="java_separator">(</span><span class="java_plain">l</span><span class="java_separator">,</span><span class="java_plain"> f</span><span class="java_separator">)</span><span class="java_plain"> </span><span class="java_operator">=&gt;</span><span class="java_plain"> </span><span class="java_type">Name</span><span class="java_separator">(</span><span class="java_plain">l</span><span class="java_separator">,</span><span class="java_plain"> f</span><span class="java_separator">)</span><span class="java_plain"/></span></span><br/><span class="Apple-style-span" style="font-size: small;"><span class="Apple-style-span" style="font-size: 13px;"><span class="java_plain">    </span><span class="java_keyword">case</span><span class="java_plain"> _ </span><span class="java_operator">=&gt;</span><span class="java_plain"> error</span><span class="java_separator">(</span><span class="java_literal">"invalid"</span><span class="java_separator">)</span><span class="java_plain"/></span></span><br/><span class="Apple-style-span" style="font-size: small;"><span class="Apple-style-span" style="font-size: 13px;"><span class="java_plain">  </span><span class="java_separator">}</span><span class="java_plain"/></span></span><br/><span class="Apple-style-span" style="font-size: small;"><span class="Apple-style-span" style="font-size: 13px;"><span class="java_separator">}</span><span class="java_plain"/></span></span><br/><span class="Apple-style-span" style="font-size: small;"><span class="Apple-style-span" style="font-size: 13px;"><span class="java_plain"/></span></span></code><code><span class="Apple-style-span" style="font-size: small;"><span class="Apple-style-span" style="font-size: 13px;"/></span></code><span class="Apple-style-span" style="font-size: small;"/><br/><span class="Apple-style-span" style="font-size: small;"><span class="Apple-style-span" style="font-size: 13px;">So the <code>Read</code> type class in Scala is generic enough to be instantiated for <i>all</i> kinds of abstractions. Note that unlike interfaces in Java, the polymorphism is not coupled with inheritance hierarchies. With interface, your abstraction needs to implement the interface statically, which means that the interface has to exist before you design your abstraction. With type classes, the abstractions for <code>Int</code> and <code>Float</code> existed well before we define the <code>Read</code> type class.</span></span><br/><span class="Apple-style-span" style="font-size: small;"><span class="Apple-style-span" style="font-size: 13px;"><br/></span></span><br/><span class="Apple-style-span" style="font-size: small;"><span class="Apple-style-span" style="font-size: 13px;">Now if we have a generic function that takes a <code>String</code>, we can make it return an instance of the type it is generic on.</span></span><br/><span class="Apple-style-span" style="font-size: small;"><span class="Apple-style-span" style="font-size: 13px;"><br/></span></span><br/><span class="Apple-style-span" style="font-size: small;"><span class="Apple-style-span" style="font-size: 13px;"><code><span class="java_keyword">def</span><span class="java_plain"> foo</span><span class="java_separator">[</span><span class="java_plain">T </span><span class="java_operator">:</span><span class="java_plain"> </span><span class="java_type">Read</span><span class="java_separator">](</span><span class="java_plain">s</span><span class="java_operator">:</span><span class="java_plain"> </span><span class="java_type">String</span><span class="java_separator">)</span><span class="java_plain"> </span><span class="java_operator">=</span><span class="java_plain"> implicitly</span><span class="java_separator">[</span><span class="java_type">Read</span><span class="java_separator">[</span><span class="java_plain">T</span><span class="java_separator">]].</span><span class="java_plain">read</span><span class="java_separator">(</span><span class="java_plain">s</span><span class="java_separator">)</span><span class="java_plain"/></code></span><code/></span><code/><br/><code><span class="Apple-style-span" style="font-size: small;"><span class="Apple-style-span" style="font-size: 13px;"><span class="java_plain"/></span></span><br/><span class="Apple-style-span" style="font-size: small;"><span class="Apple-style-span" style="font-size: 13px;"><span class="java_plain">foo</span><span class="java_separator">[</span><span class="java_type">Int</span><span class="java_separator">](</span><span class="java_literal">"123"</span><span class="java_separator">)</span><span class="java_plain"> </span><span class="java_comment">// 123</span></span></span><br/><span class="Apple-style-span" style="font-size: small;"><span class="Apple-style-span" style="font-size: 13px;"><span class="java_plain">foo</span><span class="java_separator">[</span><span class="java_type">Float</span><span class="java_separator">](</span><span class="java_literal">"123.0"</span><span class="java_separator">)</span><span class="java_plain"> </span><span class="java_comment">// 123.0</span></span></span><br/><span class="Apple-style-span" style="font-size: small;"><span class="Apple-style-span" style="font-size: 13px;"><span class="java_plain">foo</span><span class="java_separator">[</span><span class="java_type">Name</span><span class="java_separator">](</span><span class="java_literal">"debasish/ghosh"</span><span class="java_separator">)</span><span class="java_plain"> </span><span class="java_comment">// Name("ghosh", "debasish")</span></span></span><br/><span class="Apple-style-span" style="font-size: small;"><span class="Apple-style-span" style="font-size: 13px;"><span class="java_plain"/></span></span></code><code><span class="Apple-style-span" style="font-size: small;"><span class="Apple-style-span" style="font-size: 13px;"/></span></code><span class="Apple-style-span" style="font-size: small;"/><br/><span class="Apple-style-span" style="font-size: small;"><span class="Apple-style-span" style="font-size: 13px;">Ok .. so that was our generic <code>read</code> API adapting violently to already existing abstractions. In this case it's exactly the Scala variant of how simple type class instances behave in Haskell. The authors of <a href="http://www.realworldhaskell.org/blog/">Real World Haskell</a> uses the term <i>open world assumption</i> to describe this feature of the type class system.</span></span><br/><span class="Apple-style-span" style="font-size: small;"><span class="Apple-style-span" style="font-size: 13px;"><br/></span></span><br/><span class="Apple-style-span" style="font-size: small;"><span class="Apple-style-span" style="font-size: 13px;"><b>Context for selecting the API instance</b></span></span><br/><span class="Apple-style-span" style="font-size: small;"><span class="Apple-style-span" style="font-size: 13px;"><br/></span></span><br/><span class="Apple-style-span" style="font-size: small;"><span class="Apple-style-span" style="font-size: 13px;">When the function <code>foo</code> is invoked, the compiler needs to find out the exact instance of the <code>Read</code> type class from the method dictionary in case of Haskell and from the list of available implicit conversions in case of Scala. For this we specify the context bound of the generic type <code>T</code> as <code>T : Read</code>. This is same as the context of the type class that we have in Haskell.  It specifies that the method <code>foo</code> can return any type <code>T</code> provided the type is an instance of the type class <code>Read</code>. Apart from using the context bound, in Scala you can also use view bounds to implement context of a type class. The Haskell equivalent is ..</span></span><br/><span class="Apple-style-span" style="font-size: small;"><span class="Apple-style-span" style="font-size: 13px;"><br/></span></span><br/><span class="Apple-style-span" style="font-size: small;"><span class="Apple-style-span" style="font-size: 13px;"><code><span class="java_plain">foo </span><span class="java_operator">::</span><span class="java_plain"> </span><span class="java_type">Read</span><span class="java_plain"> a </span><span class="java_operator">=&gt;</span><span class="java_plain"> </span><span class="java_type">String</span><span class="java_plain"> </span><span class="java_operator">-&gt;</span><span class="java_plain"> a</span></code></span><code/></span><code/><br/><code><span class="Apple-style-span" style="font-size: small;"><span class="Apple-style-span" style="font-size: 13px;"><span class="java_plain"/></span></span></code><code><span class="Apple-style-span" style="font-size: small;"><span class="Apple-style-span" style="font-size: 13px;"/></span></code><span class="Apple-style-span" style="font-size: small;"/><br/><span class="Apple-style-span" style="font-size: small;"><span class="Apple-style-span" style="font-size: 13px;">Irrespective of Haskell or Scala, our API becomes hugely expressive through such constraints that the static type system allows us to write. And all these constraints are checked during compile time.</span></span><br/><span class="Apple-style-span" style="font-size: small;"><span class="Apple-style-span" style="font-size: 13px;"><br/></span></span><br/><span class="Apple-style-span" style="font-size: small;"><span class="Apple-style-span" style="font-size: 13px;"><b>Context in implementing specific instances</b></span></span><br/><span class="Apple-style-span" style="font-size: small;"><span class="Apple-style-span" style="font-size: 13px;"><br/></span></span><br/><span class="Apple-style-span" style="font-size: small;"><span class="Apple-style-span" style="font-size: 13px;">When defining a generic API, you can also set up a context for specific instances of the type class. Consider our <code>read</code> method for a <code>List</code> datatype in Scala. Haskell defines the instance as ..</span></span><br/><span class="Apple-style-span" style="font-size: small;"><span class="Apple-style-span" style="font-size: 13px;"><br/></span></span><br/><span class="Apple-style-span" style="font-size: small;"><span class="Apple-style-span" style="font-size: 13px;"><code><span class="java_keyword">instance</span><span class="java_plain"> </span><span class="java_type">Read</span><span class="java_plain"> a </span><span class="java_operator">=&gt;</span><span class="java_plain"> </span><span class="java_type">Read</span><span class="java_plain"> </span><span class="java_separator">[</span><span class="java_plain">a</span><span class="java_separator">]</span><span class="java_plain"> </span><span class="java_keyword">where</span><span class="java_plain"> </span><span class="java_separator">..</span><span class="java_plain"/></code></span><code/></span><code/><br/><code><span class="Apple-style-span" style="font-size: small;"><span class="Apple-style-span" style="font-size: 13px;"><span class="java_plain"/></span></span></code><code><span class="Apple-style-span" style="font-size: small;"><span class="Apple-style-span" style="font-size: 13px;"/></span></code><span class="Apple-style-span" style="font-size: small;"/><br/><span class="Apple-style-span" style="font-size: small;"><span class="Apple-style-span" style="font-size: 13px;">Note the <i>context</i> <code>Read a</code> following the <code>instance</code> keyword. This is called the <i>context of the type class instance</i> which says that we can read a <code>List</code> of <code>a</code> only if all individual <code>a</code>'s also implement the <code>Read</code> type class. </span></span><br/><span class="Apple-style-span" style="font-size: small;"><span class="Apple-style-span" style="font-size: 13px;"><br/></span></span><br/><span class="Apple-style-span" style="font-size: small;"><span class="Apple-style-span" style="font-size: 13px;">We do this in Scala using conditional implicits as ..</span></span><br/><span class="Apple-style-span" style="font-size: small;"><span class="Apple-style-span" style="font-size: 13px;"><br/></span></span><br/><span class="Apple-style-span" style="font-size: small;"><span class="Apple-style-span" style="font-size: 13px;"><code><span class="java_keyword">implicit</span><span class="java_plain"> </span><span class="java_keyword">def</span><span class="java_plain"> </span><span class="java_type">ListRead</span><span class="java_separator">[</span><span class="java_plain">A</span><span class="java_separator">](</span><span class="java_keyword">implicit</span><span class="java_plain"> r</span><span class="java_operator">:</span><span class="java_plain"> </span><span class="java_type">Read</span><span class="java_separator">[</span><span class="java_plain">A</span><span class="java_separator">])</span><span class="java_plain"> </span><span class="java_operator">=</span><span class="java_plain"> </span></code></span><code/></span><code/><br/><code><span class="Apple-style-span" style="font-size: small;"><span class="Apple-style-span" style="font-size: 13px;"><span class="java_plain">  </span><span class="java_keyword">new</span><span class="java_plain"> </span><span class="java_type">Read</span><span class="java_separator">[</span><span class="java_type">List</span><span class="java_separator">[</span><span class="java_plain">A</span><span class="java_separator">]]</span><span class="java_plain"> </span><span class="java_separator">{</span><span class="java_plain"/></span></span><br/><span class="Apple-style-span" style="font-size: small;"><span class="Apple-style-span" style="font-size: 13px;"><span class="java_plain">    </span><span class="java_keyword">def</span><span class="java_plain"> read</span><span class="java_separator">(</span><span class="java_plain">s</span><span class="java_operator">:</span><span class="java_plain"> </span><span class="java_type">String</span><span class="java_separator">)</span><span class="java_plain"> </span><span class="java_operator">=</span><span class="java_plain"> </span><span class="java_separator">{</span><span class="java_plain"/></span></span><br/><span class="Apple-style-span" style="font-size: small;"><span class="Apple-style-span" style="font-size: 13px;"><span class="java_plain">      </span><span class="java_keyword">val</span><span class="java_plain"> es </span><span class="java_operator">=</span><span class="java_plain"> s</span><span class="java_separator">.</span><span class="java_plain">split</span><span class="java_separator">(</span><span class="java_literal">" "</span><span class="java_separator">).</span><span class="java_plain">toList</span></span></span><br/><span class="Apple-style-span" style="font-size: small;"><span class="Apple-style-span" style="font-size: 13px;"><span class="java_plain">      es</span><span class="java_separator">.</span><span class="java_plain">map</span><span class="java_separator">(</span><span class="java_plain">r</span><span class="java_separator">.</span><span class="java_plain">read</span><span class="java_separator">(</span><span class="java_plain">_</span><span class="java_separator">))</span><span class="java_plain"/></span></span><br/><span class="Apple-style-span" style="font-size: small;"><span class="Apple-style-span" style="font-size: 13px;"><span class="java_plain">    </span><span class="java_separator">}</span><span class="java_plain"/></span></span><br/><span class="Apple-style-span" style="font-size: small;"><span class="Apple-style-span" style="font-size: 13px;"><span class="java_plain">  </span><span class="java_separator">}</span><span class="java_plain"/></span></span><br/><span class="Apple-style-span" style="font-size: small;"><span class="Apple-style-span" style="font-size: 13px;"><span class="java_plain"/></span></span></code><code><span class="Apple-style-span" style="font-size: small;"><span class="Apple-style-span" style="font-size: 13px;"/></span></code><span class="Apple-style-span" style="font-size: small;"/><br/><span class="Apple-style-span" style="font-size: small;"><span class="Apple-style-span" style="font-size: 13px;">The implicit definition itself takes another implicit argument to validate <i>during compile time</i> that the individual elements of the <code>List</code> also are instances of the type class. This is similar to what the context does in case of Haskell's type class instantiation.</span></span><br/><span class="Apple-style-span" style="font-size: small;"><span class="Apple-style-span" style="font-size: 13px;"><br/></span></span><br/><span class="Apple-style-span" style="font-size: small;"><span class="Apple-style-span" style="font-size: 13px;"><code><span class="java_plain">foo</span><span class="java_separator">[</span><span class="java_type">List</span><span class="java_separator">[</span><span class="java_type">Int</span><span class="java_separator">]](</span><span class="java_literal">"12 234 45 678"</span><span class="java_separator">)</span><span class="java_plain"> </span><span class="java_comment">// List(12, 234, 45, 678)</span></code></span><code/></span><code/><br/><code><span class="Apple-style-span" style="font-size: small;"><span class="Apple-style-span" style="font-size: 13px;"><span class="java_plain">foo</span><span class="java_separator">[</span><span class="java_type">List</span><span class="java_separator">[</span><span class="java_type">Float</span><span class="java_separator">]](</span><span class="java_literal">"12.0 234.0 45.0 678.0"</span><span class="java_separator">)</span><span class="java_plain"> </span><span class="java_comment">// List(12.0, 234.0, 45.0, 678.0)</span></span></span><br/><span class="Apple-style-span" style="font-size: small;"><span class="Apple-style-span" style="font-size: 13px;"><span class="java_plain">foo</span><span class="java_separator">[</span><span class="java_type">List</span><span class="java_separator">[</span><span class="java_type">Name</span><span class="java_separator">]](</span><span class="java_literal">"debasish/ghosh maulindu/chatterjee nilanjan/das"</span><span class="java_separator">)</span><span class="java_plain"/></span></span><br/><span class="Apple-style-span" style="font-size: small;"><span class="Apple-style-span" style="font-size: 13px;"><span class="java_plain">  </span><span class="java_comment">// List(Name("ghosh", "debasish"), Name("chatterjee", "maulindu"), Name("das", "nilanjan"))</span></span></span><br/><span class="Apple-style-span" style="font-size: small;"><span class="Apple-style-span" style="font-size: 13px;"><span class="java_plain"/></span></span></code><code><span class="Apple-style-span" style="font-size: small;"><span class="Apple-style-span" style="font-size: 13px;"/></span></code><span class="Apple-style-span" style="font-size: small;"/><br/><span class="Apple-style-span" style="font-size: small;"><span class="Apple-style-span" style="font-size: 13px;">As part of common extensions of GHCI, Haskell also provides support for overlapping instances of type classes ..</span></span><br/><span class="Apple-style-span" style="font-size: small;"><span class="Apple-style-span" style="font-size: 13px;"><br/></span></span><br/><span class="Apple-style-span" style="font-size: small;"><span class="Apple-style-span" style="font-size: 13px;"><code><span class="java_keyword">instance</span><span class="java_plain"> </span><span class="java_type">Read</span><span class="java_plain"> a </span><span class="java_operator">=&gt;</span><span class="java_plain"> </span><span class="java_type">Read</span><span class="java_plain"> </span><span class="java_separator">[</span><span class="java_plain">a</span><span class="java_separator">]</span><span class="java_plain"> </span><span class="java_keyword">where</span><span class="java_plain"> </span><span class="java_separator">..</span><span class="java_plain"/></code></span><code/></span><code/><br/><code><span class="Apple-style-span" style="font-size: small;"><span class="Apple-style-span" style="font-size: 13px;"><span class="java_keyword">instance</span><span class="java_plain"> </span><span class="java_type">Read</span><span class="java_plain"> </span><span class="java_separator">[</span><span class="java_type">Int</span><span class="java_separator">]</span><span class="java_plain"> </span><span class="java_keyword">where</span><span class="java_plain"> </span><span class="java_separator">..</span><span class="java_plain"/></span></span><br/><span class="Apple-style-span" style="font-size: small;"><span class="Apple-style-span" style="font-size: 13px;"><span class="java_plain"/></span></span></code><code><span class="Apple-style-span" style="font-size: small;"><span class="Apple-style-span" style="font-size: 13px;"/></span></code><span class="Apple-style-span" style="font-size: small;"/><br/><span class="Apple-style-span" style="font-size: small;"><span class="Apple-style-span" style="font-size: 13px;">In such cases although there are two possible matches for <code>[Int]</code>, the compiler can make an unambiguous decision and select the most specific instance. With Scala, there is no such ambiguity to be resolved since Scala anyway allows multiple implementations of the same type class and it's up to the user to import the specific one into the module.</span></span><br/><span class="Apple-style-span" style="font-size: small;"><span class="Apple-style-span" style="font-size: 13px;"><br/></span></span><br/><span class="Apple-style-span" style="font-size: small;"><span class="Apple-style-span" style="font-size: 13px;">In this post I discussed the power that you get with type class based generic API design. In functional languages like Haskell, type classes are the most potent way to implement extensible APIs for the open world. Of course in object functional languages like Scala, you also have the power of subtyping, which comes good in many circumstances. It will be interesting to come up with a comparative analysis of situations when we prefer one to the other. But that's up for some other day, some other post ..</span></span><br/><span class="Apple-style-span" style="font-size: small;"><span class="Apple-style-span" style="font-size: 13px;"><br/></span></span></span><div class="blogger-post-footer"><img alt="" height="1" src="https://blogger.googleusercontent.com/tracker/22587889-6180939564075434164?l=debasishg.blogspot.com" width="1"/></div></div>
    </content>
    <updated>2010-09-03T05:17:01Z</updated>
    <published>2010-09-03T05:17:00Z</published>
    <category scheme="http://www.blogger.com/atom/ns#" term="haskell"/>
    <category scheme="http://www.blogger.com/atom/ns#" term="scala"/>
    <author>
      <name>Debasish</name>
      <email>ghosh.debasish@gmail.com</email>
      <uri>http://www.blogger.com/profile/01613713587074301135</uri>
    </author>
    <source>
      <id>tag:blogger.com,1999:blog-22587889</id>
      <author>
        <name>Debasish</name>
        <email>ghosh.debasish@gmail.com</email>
        <uri>http://www.blogger.com/profile/01613713587074301135</uri>
      </author>
      <link href="http://debasishg.blogspot.com/feeds/posts/full" rel="http://schemas.google.com/g/2005#feed" type="application/atom+xml"/>
      <link href="http://debasishg.blogspot.com/" rel="alternate" type="text/html"/>
      <link href="http://debasishg.blogspot.com/feeds/posts/full?start-index=4&amp;max-results=3" rel="next" type="application/atom+xml"/>
      <link href="http://feeds.feedburner.com/RuminationsOfAProgrammer" rel="self" type="application/atom+xml"/>
      <link href="http://pubsubhubbub.appspot.com/" rel="hub" type="text/html"/>
      <subtitle>A programmer's blog - will deal with everything that relates to a programmer. Occasionally, it will contain some humour, some politics and some sport news.</subtitle>
      <title>Ruminations of a Programmer</title>
      <updated>2010-09-03T15:56:25Z</updated>
    </source>
  </entry>

  <entry>
    <id>http://code.technically.us/post/1054548581</id>
    <link href="http://code.technically.us/post/1054548581" rel="alternate" type="text/html"/>
    <title>Dispatch 0.7.6</title>
    <summary type="xhtml"><div xmlns="http://www.w3.org/1999/xhtml"><a href="http://implicit.ly/dispatch-076">Dispatch 0.7.6</a>: <p>Broader redirect handling, support for Google ClientLogin, a JSON extractor for optional properties, and OAuth compatibility with Twitter’s streaming API.</p></div>
    </summary>
    <updated>2010-09-02T19:41:39Z</updated>
    <category term="Dispatch"/>
    <category term="Scala"/>
    <category term="Twitter"/>
    <category term="OAuth"/>
    <category term="ClientLogin"/>
    <source>
      <id>http://code.technically.us/</id>
      <author>
        <name>Coderspiel</name>
      </author>
      <link href="http://tumblr.superfeedr.com/" rel="hub" type="text/html"/>
      <link href="http://code.technically.us/" rel="alternate" type="text/html"/>
      <link href="http://code.technically.us/rss" rel="self" type="application/rss+xml"/>
      <title>Coderspiel</title>
      <updated>2010-09-09T03:00:39Z</updated>
    </source>
  </entry>

  <entry>
    <id>http://code.technically.us/post/1053900508</id>
    <link href="http://code.technically.us/post/1053900508" rel="alternate" type="text/html"/>
    <title>"simple-build-tool plugin to publish and distribute your Scala projects using Github as Ivy..."</title>
    <summary type="xhtml"><div xmlns="http://www.w3.org/1999/xhtml">“simple-build-tool plugin to publish and distribute your Scala projects using Github as Ivy repository”<br/><br/> - <em><a href="http://github.com/siasia/plugin">siasia’s plugin at master - GitHub</a></em></div>
    </summary>
    <updated>2010-09-02T16:00:27Z</updated>
    <category term="sbt"/>
    <category term="plugins"/>
    <category term="github"/>
    <category term="Software distribution"/>
    <category term="Scala"/>
    <source>
      <id>http://code.technically.us/</id>
      <author>
        <name>Coderspiel</name>
      </author>
      <link href="http://tumblr.superfeedr.com/" rel="hub" type="text/html"/>
      <link href="http://code.technically.us/" rel="alternate" type="text/html"/>
      <link href="http://code.technically.us/rss" rel="self" type="application/rss+xml"/>
      <title>Coderspiel</title>
      <updated>2010-09-09T03:00:39Z</updated>
    </source>
  </entry>

  <entry>
    <id>http://code.technically.us/post/1053078930</id>
    <link href="http://code.technically.us/post/1053078930" rel="alternate" type="text/html"/>
    <title>Samsung’s idea of bicycling with technology looks more...</title>
    <summary type="xhtml"><div xmlns="http://www.w3.org/1999/xhtml"><img src="http://24.media.tumblr.com/tumblr_l84dmdALId1qb6dplo1_500.jpg"/><br/><br/><p><a href="http://gizmodo.com/5628214/samsung-galaxy-tab-lifestyle-gallery/gallery/5">Samsung’s idea of bicycling with technology</a> looks more fun, less authorized <a href="http://code.technically.us/post/912950746/apple-to-bring-much-needed-authorization-to">than Apple’s</a></p></div>
    </summary>
    <updated>2010-09-02T12:35:00Z</updated>
    <category term="Cycling"/>
    <category term="Samsung"/>
    <category term="Chillness"/>
    <category term="Android"/>
    <category term="Gizmodo"/>
    <source>
      <id>http://code.technically.us/</id>
      <author>
        <name>Coderspiel</name>
      </author>
      <link href="http://tumblr.superfeedr.com/" rel="hub" type="text/html"/>
      <link href="http://code.technically.us/" rel="alternate" type="text/html"/>
      <link href="http://code.technically.us/rss" rel="self" type="application/rss+xml"/>
      <title>Coderspiel</title>
      <updated>2010-09-09T03:00:39Z</updated>
    </source>
  </entry>

  <entry xml:lang="en">
    <id>http://codemonkeyism.com/?p=1986</id>
    <link href="http://feedproxy.google.com/~r/stephansblog/~3/u7df-OCMZsE/" rel="alternate" type="text/html"/>
    <link href="http://codemonkeyism.com/configuration-files/#comments" rel="replies" type="text/html"/>
    <link href="http://codemonkeyism.com/configuration-files/feed/atom/" rel="replies" type="application/atom+xml"/>
    <title xml:lang="en">Better Configuration Files</title>
    <summary type="xhtml" xml:lang="en"><div xmlns="http://www.w3.org/1999/xhtml">Over the years I have seen many configuration files. Most of them were unusable. There are many reasons for unusable configuration files. What I’ve learned from looking at large configurations are those main points:
1. Values
Often configuration files use the wrong values. Developers tend to use true/false for switching options on and off. 

track-users = true

The [...]<img height="1" src="http://feeds.feedburner.com/~r/stephansblog/~4/u7df-OCMZsE" width="1"/></div>
    </summary>
    <updated>2010-09-02T11:45:32Z</updated>
    <published>2010-09-01T15:02:32Z</published>
    <category scheme="http://codemonkeyism.com" term="Java"/><feedburner:origLink xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0">http://codemonkeyism.com/configuration-files/</feedburner:origLink>
    <author>
      <name>stephan</name>
      <uri>http://codemonkeyism.com</uri>
    </author>
    <source>
      <id>http://codemonkeyism.com/feed/atom/</id>
      <link href="http://codemonkeyism.com" rel="alternate" type="text/html"/>
      <link href="http://feeds.feedburner.com/stephansblog" rel="self" type="application/atom+xml"/>
      <link href="http://pubsubhubbub.appspot.com/" rel="hub" type="text/html"/>
      <title xml:lang="en">Code Monkeyism</title>
      <updated>2010-09-08T05:05:52Z</updated>
    </source>
  </entry>

  <entry xml:lang="en">
    <id>http://www.decodified.com/scala/2010/09/02/scala-collections-api-charted-out/</id>
    <link href="http://www.decodified.com/scala/2010/09/02/scala-collections-api-charted-out.html" rel="alternate" type="text/html"/>
    <title>Scala Collections API Charted Out</title>
    <summary type="xhtml"><div xmlns="http://www.w3.org/1999/xhtml"><p>The revamped collections API is one of cornerstones of the recently released Scala version 2.8.<br/>It provides an incredibly rich toolset for working with object collections and as such is one of the most important parts of the Scala runtime library. The Scala team has made an effort to provide thorough documentation uncovering its feature breadth, the most important sources of information...</p></div>
    </summary>
    <updated>2010-09-02T07:00:00Z</updated>
    <category scheme="http://www.decodified.com/categories/scala" term="scala"/>
    <source>
      <id>http://www.decodified.com</id>
      <author>
        <name>Mathias</name>
      </author>
      <link href="http://www.decodified.com" rel="alternate" type="text/html"/>
      <link href="http://feeds.feedburner.com/decodified" rel="self" type="application/rss+xml"/>
      <link href="http://pubsubhubbub.appspot.com/" rel="hub" type="text/html"/>
      <rights>Copyright 2010, decodified.com</rights>
      <subtitle>between code and cleartext</subtitle>
      <title>decodified</title>
      <updated>2010-09-03T09:16:29Z</updated>
    </source>
  </entry>

  <entry>
    <id>http://code.technically.us/post/1048322551</id>
    <link href="http://code.technically.us/post/1048322551" rel="alternate" type="text/html"/>
    <title>Obama administration: "Piracy is flat, unadulterated theft"</title>
    <summary type="xhtml"><div xmlns="http://www.w3.org/1999/xhtml"><a href="http://arstechnica.com/tech-policy/news/2010/08/obama-administration-piracy-is-flat-unadulterated-theft.ars">Obama administration: "Piracy is flat, unadulterated theft"</a>: <p>If copyright violations are <em>just like theft</em> (and they are not, if you think about it for 1.5 seconds), why are the penalties millions of dollars more than for shoplifting?</p></div>
    </summary>
    <updated>2010-09-01T15:49:36Z</updated>
    <category term="Bad analogies"/>
    <category term="Obama"/>
    <category term="Dumb property"/>
    <category term="Old media"/>
    <category term="Ars"/>
    <source>
      <id>http://code.technically.us/</id>
      <author>
        <name>Coderspiel</name>
      </author>
      <link href="http://tumblr.superfeedr.com/" rel="hub" type="text/html"/>
      <link href="http://code.technically.us/" rel="alternate" type="text/html"/>
      <link href="http://code.technically.us/rss" rel="self" type="application/rss+xml"/>
      <title>Coderspiel</title>
      <updated>2010-09-09T03:00:39Z</updated>
    </source>
  </entry>

  <entry xml:lang="en">
    <id>http://blog.tmorris.net/?p=812</id>
    <link href="http://blog.tmorris.net/even-further-understanding-scalaoption-part-2/" rel="alternate" type="text/html"/>
    <title>Even Further Understanding scala.Option (part 2)</title>
    <summary>As a follow-on to Further Understanding scala.Option, following are another 10 exercises (numbered 16 to 25). Included are solutions to the original 1 to 15 exercises. Instructions are in the comments.

// Scala version 2.8.0.final
// http://scala-tools.org/repo-releases/org/scala-tools/testing/scalacheck_2.8.0/1.7/scalacheck_2.8.0-1.7.jar
 
 
/*
 
  PART 1
  ======
  Below are 15 exercises numbered 1 to 15. The task is to emulate the [...]</summary>
    <content type="xhtml"><div xmlns="http://www.w3.org/1999/xhtml"><p>As a follow-on to <a href="http://blog.tmorris.net/further-understanding-scalaoption/">Further Understanding scala.Option</a>, following are another 10 exercises (numbered 16 to 25). Included are solutions to the original 1 to 15 exercises. Instructions are in the comments.</p>

<div class="wp_syntax"><div class="code"><pre class="scala"><span style="color: #008000; font-style: italic;">// Scala version 2.8.0.final</span>
<span style="color: #008000; font-style: italic;">// http://scala-tools.org/repo-releases/org/scala-tools/testing/scalacheck_2.8.0/1.7/scalacheck_2.8.0-1.7.jar</span>
 
 
<span style="color: #00ff00; font-style: italic;">/*
 
  PART 1
  ======
  Below are 15 exercises numbered 1 to 15. The task is to emulate the scala.Option API
  without using Some/None subtypes, but instead using a fold (called a
  catamorphism).
 
  A couple of functions are already done (map, get)
  to be used as an example. ScalaCheck tests are given below to
  verify the work. The desired result is to have all tests passing.
 
  The 15th exercise is not available in the existing Scala API so
  instructions are given in the comments.
 
 
  Part 2
  ======
 
  Below are 10 exercises numbered 16 to 25. The task is to implement additional
  methods for the Optional data type. These methods are not provided in the
  scala.Option API so to determine the correct result requires reading the method
  type signature and ensuring that the tests pass.
 
  The 25th exercise is notable in that its signature says nothing about
  scala.Option yet it is usable for Option (see the test for example).
 
 
  Revision History
  ================
 
  23/08/2010
  * Initial revision
 
  ----------------
 
  23/08/2010
  * Fixed prop_getOrElse. Thanks Michael Bayne.
 
  ----------------
 
  26/08/2010
  * Add lazy annotation to orElse method.
 
  ----------------
 
  01/09/2010
  Added Part 2
 
  02/09/2010
  * Fixed mapOptionals test (why wasn't it failing?). Thanks Alec Zorab.
  * Added comments including *** special note ***
 
*/</span>
 
 
<span style="color: #0000ff; font-weight: bold;">trait</span> Optional<span style="color: #F78811;">[</span>A<span style="color: #F78811;">]</span> <span style="color: #F78811;">{</span>
  <span style="color: #008000; font-style: italic;">// single abstract method</span>
  <span style="color: #0000ff; font-weight: bold;">def</span> fold<span style="color: #F78811;">[</span>X<span style="color: #F78811;">]</span><span style="color: #F78811;">(</span>some<span style="color: #000080;">:</span> A <span style="color: #000080;">=&gt;</span> X, none<span style="color: #000080;">:</span> <span style="color: #000080;">=&gt;</span> X<span style="color: #F78811;">)</span><span style="color: #000080;">:</span> X
 
  <span style="color: #0000ff; font-weight: bold;">import</span> Optional.<span style="color: #000080;">_</span>
 
  <span style="color: #008000; font-style: italic;">// Done for you.</span>
  <span style="color: #0000ff; font-weight: bold;">def</span> map<span style="color: #F78811;">[</span>B<span style="color: #F78811;">]</span><span style="color: #F78811;">(</span>f<span style="color: #000080;">:</span> A <span style="color: #000080;">=&gt;</span> B<span style="color: #F78811;">)</span><span style="color: #000080;">:</span> Optional<span style="color: #F78811;">[</span>B<span style="color: #F78811;">]</span> <span style="color: #000080;">=</span>
    fold<span style="color: #F78811;">(</span>f andThen some, none<span style="color: #F78811;">[</span>B<span style="color: #F78811;">]</span><span style="color: #F78811;">)</span>
 
  <span style="color: #008000; font-style: italic;">// Done for you.</span>
  <span style="color: #008000; font-style: italic;">// WARNING: undefined for None</span>
  <span style="color: #0000ff; font-weight: bold;">def</span> get<span style="color: #000080;">:</span> A <span style="color: #000080;">=</span>
    fold<span style="color: #F78811;">(</span>a <span style="color: #000080;">=&gt;</span> a, error<span style="color: #F78811;">(</span><span style="color: #6666FF;">"None.get"</span><span style="color: #F78811;">)</span><span style="color: #F78811;">)</span>
 
  <span style="color: #008000; font-style: italic;">// Exercise 1</span>
  <span style="color: #0000ff; font-weight: bold;">def</span> flatMap<span style="color: #F78811;">[</span>B<span style="color: #F78811;">]</span><span style="color: #F78811;">(</span>f<span style="color: #000080;">:</span> A <span style="color: #000080;">=&gt;</span> Optional<span style="color: #F78811;">[</span>B<span style="color: #F78811;">]</span><span style="color: #F78811;">)</span><span style="color: #000080;">:</span> Optional<span style="color: #F78811;">[</span>B<span style="color: #F78811;">]</span> <span style="color: #000080;">=</span>
    fold<span style="color: #F78811;">(</span>f, none<span style="color: #F78811;">)</span>
 
  <span style="color: #008000; font-style: italic;">// Exercise 2</span>
  <span style="color: #008000; font-style: italic;">// Rewrite map but use flatMap, not fold.</span>
  <span style="color: #0000ff; font-weight: bold;">def</span> mapAgain<span style="color: #F78811;">[</span>B<span style="color: #F78811;">]</span><span style="color: #F78811;">(</span>f<span style="color: #000080;">:</span> A <span style="color: #000080;">=&gt;</span> B<span style="color: #F78811;">)</span><span style="color: #000080;">:</span> Optional<span style="color: #F78811;">[</span>B<span style="color: #F78811;">]</span> <span style="color: #000080;">=</span>
    flatMap<span style="color: #F78811;">(</span>f andThen some<span style="color: #F78811;">)</span>
 
  <span style="color: #008000; font-style: italic;">// Exercise 3</span>
  <span style="color: #0000ff; font-weight: bold;">def</span> getOrElse<span style="color: #F78811;">(</span>e<span style="color: #000080;">:</span> <span style="color: #000080;">=&gt;</span> A<span style="color: #F78811;">)</span><span style="color: #000080;">:</span> A <span style="color: #000080;">=</span>
    fold<span style="color: #F78811;">(</span>s <span style="color: #000080;">=&gt;</span> s, e<span style="color: #F78811;">)</span>
 
  <span style="color: #008000; font-style: italic;">// Exercise 4</span>
  <span style="color: #0000ff; font-weight: bold;">def</span> filter<span style="color: #F78811;">(</span>p<span style="color: #000080;">:</span> A <span style="color: #000080;">=&gt;</span> <span style="color: #9999cc; font-weight: bold;">Boolean</span><span style="color: #F78811;">)</span><span style="color: #000080;">:</span> Optional<span style="color: #F78811;">[</span>A<span style="color: #F78811;">]</span> <span style="color: #000080;">=</span>
    fold<span style="color: #F78811;">(</span>a <span style="color: #000080;">=&gt;</span> <span style="color: #0000ff; font-weight: bold;">if</span><span style="color: #F78811;">(</span>p<span style="color: #F78811;">(</span>a<span style="color: #F78811;">)</span><span style="color: #F78811;">)</span> some<span style="color: #F78811;">(</span>a<span style="color: #F78811;">)</span> <span style="color: #0000ff; font-weight: bold;">else</span> none, none<span style="color: #F78811;">)</span>
 
  <span style="color: #008000; font-style: italic;">// Exercise 5</span>
  <span style="color: #0000ff; font-weight: bold;">def</span> exists<span style="color: #F78811;">(</span>p<span style="color: #000080;">:</span> A <span style="color: #000080;">=&gt;</span> <span style="color: #9999cc; font-weight: bold;">Boolean</span><span style="color: #F78811;">)</span><span style="color: #000080;">:</span> <span style="color: #9999cc; font-weight: bold;">Boolean</span> <span style="color: #000080;">=</span>
    fold<span style="color: #F78811;">(</span>p, <span style="color: #0000ff; font-weight: bold;">false</span><span style="color: #F78811;">)</span>
 
  <span style="color: #008000; font-style: italic;">// Exercise 6</span>
  <span style="color: #0000ff; font-weight: bold;">def</span> forall<span style="color: #F78811;">(</span>p<span style="color: #000080;">:</span> A <span style="color: #000080;">=&gt;</span> <span style="color: #9999cc; font-weight: bold;">Boolean</span><span style="color: #F78811;">)</span><span style="color: #000080;">:</span> <span style="color: #9999cc; font-weight: bold;">Boolean</span> <span style="color: #000080;">=</span>
    fold<span style="color: #F78811;">(</span>p, <span style="color: #0000ff; font-weight: bold;">true</span><span style="color: #F78811;">)</span>
 
  <span style="color: #008000; font-style: italic;">// Exercise 7</span>
  <span style="color: #0000ff; font-weight: bold;">def</span> foreach<span style="color: #F78811;">(</span>f<span style="color: #000080;">:</span> A <span style="color: #000080;">=&gt;</span> Unit<span style="color: #F78811;">)</span><span style="color: #000080;">:</span> Unit <span style="color: #000080;">=</span>
    fold<span style="color: #F78811;">(</span>f, <span style="color: #F78811;">(</span><span style="color: #F78811;">)</span><span style="color: #F78811;">)</span>
 
  <span style="color: #008000; font-style: italic;">// Exercise 8</span>
  <span style="color: #0000ff; font-weight: bold;">def</span> isDefined<span style="color: #000080;">:</span> <span style="color: #9999cc; font-weight: bold;">Boolean</span> <span style="color: #000080;">=</span>
    fold<span style="color: #F78811;">(</span><span style="color: #000080;">_</span> <span style="color: #000080;">=&gt;</span> <span style="color: #0000ff; font-weight: bold;">true</span>, <span style="color: #0000ff; font-weight: bold;">false</span><span style="color: #F78811;">)</span>
 
  <span style="color: #008000; font-style: italic;">// Exercise 9</span>
  <span style="color: #0000ff; font-weight: bold;">def</span> isEmpty<span style="color: #000080;">:</span> <span style="color: #9999cc; font-weight: bold;">Boolean</span> <span style="color: #000080;">=</span>
    fold<span style="color: #F78811;">(</span><span style="color: #000080;">_</span> <span style="color: #000080;">=&gt;</span> <span style="color: #0000ff; font-weight: bold;">false</span>, <span style="color: #0000ff; font-weight: bold;">true</span><span style="color: #F78811;">)</span>
 
  <span style="color: #008000; font-style: italic;">// Exercise 10</span>
  <span style="color: #0000ff; font-weight: bold;">def</span> orElse<span style="color: #F78811;">(</span>o<span style="color: #000080;">:</span> <span style="color: #000080;">=&gt;</span> Optional<span style="color: #F78811;">[</span>A<span style="color: #F78811;">]</span><span style="color: #F78811;">)</span><span style="color: #000080;">:</span> Optional<span style="color: #F78811;">[</span>A<span style="color: #F78811;">]</span> <span style="color: #000080;">=</span>
    fold<span style="color: #F78811;">(</span><span style="color: #000080;">_</span> <span style="color: #000080;">=&gt;</span> <span style="color: #0000ff; font-weight: bold;">this</span>, o<span style="color: #F78811;">)</span>
 
  <span style="color: #008000; font-style: italic;">// Exercise 11</span>
  <span style="color: #0000ff; font-weight: bold;">def</span> toLeft<span style="color: #F78811;">[</span>X<span style="color: #F78811;">]</span><span style="color: #F78811;">(</span>right<span style="color: #000080;">:</span> <span style="color: #000080;">=&gt;</span> X<span style="color: #F78811;">)</span><span style="color: #000080;">:</span> Either<span style="color: #F78811;">[</span>A, X<span style="color: #F78811;">]</span> <span style="color: #000080;">=</span>
    fold<span style="color: #F78811;">(</span>Left<span style="color: #F78811;">(</span><span style="color: #000080;">_</span><span style="color: #F78811;">)</span>, Right<span style="color: #F78811;">(</span>right<span style="color: #F78811;">)</span><span style="color: #F78811;">)</span>
 
  <span style="color: #008000; font-style: italic;">// Exercise 12</span>
  <span style="color: #0000ff; font-weight: bold;">def</span> toRight<span style="color: #F78811;">[</span>X<span style="color: #F78811;">]</span><span style="color: #F78811;">(</span>left<span style="color: #000080;">:</span> <span style="color: #000080;">=&gt;</span> X<span style="color: #F78811;">)</span><span style="color: #000080;">:</span> Either<span style="color: #F78811;">[</span>X, A<span style="color: #F78811;">]</span> <span style="color: #000080;">=</span>
    fold<span style="color: #F78811;">(</span>Right<span style="color: #F78811;">(</span><span style="color: #000080;">_</span><span style="color: #F78811;">)</span>, Left<span style="color: #F78811;">(</span>left<span style="color: #F78811;">)</span><span style="color: #F78811;">)</span>
 
  <span style="color: #008000; font-style: italic;">// Exercise 13</span>
  <span style="color: #0000ff; font-weight: bold;">def</span> toList<span style="color: #000080;">:</span> List<span style="color: #F78811;">[</span>A<span style="color: #F78811;">]</span> <span style="color: #000080;">=</span>
    fold<span style="color: #F78811;">(</span>List<span style="color: #F78811;">(</span><span style="color: #000080;">_</span><span style="color: #F78811;">)</span>, Nil<span style="color: #F78811;">)</span>
 
  <span style="color: #008000; font-style: italic;">// Exercise 14</span>
  <span style="color: #0000ff; font-weight: bold;">def</span> iterator<span style="color: #000080;">:</span> Iterator<span style="color: #F78811;">[</span>A<span style="color: #F78811;">]</span> <span style="color: #000080;">=</span>
    fold<span style="color: #F78811;">(</span>Iterator.<span style="color: #000000;">single</span><span style="color: #F78811;">(</span><span style="color: #000080;">_</span><span style="color: #F78811;">)</span>, Iterator.<span style="color: #000000;">empty</span><span style="color: #F78811;">)</span>
 
  <span style="color: #008000; font-style: italic;">// Exercise 15 The Clincher!</span>
  <span style="color: #008000; font-style: italic;">// Return a none value if either this or the argument is none.</span>
  <span style="color: #008000; font-style: italic;">// Otherwise apply the function to the argument in some.</span>
  <span style="color: #008000; font-style: italic;">// Don't be afraid to use functions you have written.</span>
  <span style="color: #008000; font-style: italic;">// Better style, more points!</span>
  <span style="color: #0000ff; font-weight: bold;">def</span> applic<span style="color: #F78811;">[</span>B<span style="color: #F78811;">]</span><span style="color: #F78811;">(</span>f<span style="color: #000080;">:</span> Optional<span style="color: #F78811;">[</span>A <span style="color: #000080;">=&gt;</span> B<span style="color: #F78811;">]</span><span style="color: #F78811;">)</span><span style="color: #000080;">:</span> Optional<span style="color: #F78811;">[</span>B<span style="color: #F78811;">]</span> <span style="color: #000080;">=</span>
    f flatMap map
 
  <span style="color: #008000; font-style: italic;">// Utility</span>
  <span style="color: #0000ff; font-weight: bold;">def</span> toOption<span style="color: #000080;">:</span> Option<span style="color: #F78811;">[</span>A<span style="color: #F78811;">]</span> <span style="color: #000080;">=</span> fold<span style="color: #F78811;">(</span>Some<span style="color: #F78811;">(</span><span style="color: #000080;">_</span><span style="color: #F78811;">)</span>, None<span style="color: #F78811;">)</span>
 
  <span style="color: #008000; font-style: italic;">// Utility</span>
  <span style="color: #0000ff; font-weight: bold;">override</span> <span style="color: #0000ff; font-weight: bold;">def</span> toString <span style="color: #000080;">=</span> 
    fold<span style="color: #F78811;">(</span><span style="color: #6666FF;">"some["</span> + <span style="color: #000080;">_</span> + <span style="color: #6666FF;">"]"</span>, <span style="color: #6666FF;">"none"</span><span style="color: #F78811;">)</span>
 
  <span style="color: #008000; font-style: italic;">// Utility</span>
  <span style="color: #0000ff; font-weight: bold;">override</span> <span style="color: #0000ff; font-weight: bold;">def</span> equals<span style="color: #F78811;">(</span>o<span style="color: #000080;">:</span> Any<span style="color: #F78811;">)</span> <span style="color: #000080;">=</span>
    o.<span style="color: #000000;">isInstanceOf</span><span style="color: #F78811;">[</span>Optional<span style="color: #F78811;">[</span><span style="color: #000080;">_</span><span style="color: #F78811;">]</span><span style="color: #F78811;">]</span> <span style="color: #000080;">&amp;&amp;</span> <span style="color: #F78811;">{</span>
      <span style="color: #0000ff; font-weight: bold;">val</span> q <span style="color: #000080;">=</span> o.<span style="color: #000000;">asInstanceOf</span><span style="color: #F78811;">[</span>Optional<span style="color: #F78811;">[</span><span style="color: #000080;">_</span><span style="color: #F78811;">]</span><span style="color: #F78811;">]</span>
      fold<span style="color: #F78811;">(</span>a <span style="color: #000080;">=&gt;</span> q.<span style="color: #000000;">exists</span><span style="color: #F78811;">(</span>a <span style="color: #000080;">==</span> <span style="color: #000080;">_</span><span style="color: #F78811;">)</span>,
           q.<span style="color: #000000;">isEmpty</span><span style="color: #F78811;">)</span>
    <span style="color: #F78811;">}</span>
<span style="color: #F78811;">}</span>
 
<span style="color: #0000ff; font-weight: bold;">object</span> Optional <span style="color: #F78811;">{</span>
  <span style="color: #008000; font-style: italic;">// Done for you</span>
  <span style="color: #0000ff; font-weight: bold;">def</span> none<span style="color: #F78811;">[</span>A<span style="color: #F78811;">]</span><span style="color: #000080;">:</span> Optional<span style="color: #F78811;">[</span>A<span style="color: #F78811;">]</span> <span style="color: #000080;">=</span> <span style="color: #0000ff; font-weight: bold;">new</span> Optional<span style="color: #F78811;">[</span>A<span style="color: #F78811;">]</span> <span style="color: #F78811;">{</span>
    <span style="color: #0000ff; font-weight: bold;">def</span> fold<span style="color: #F78811;">[</span>X<span style="color: #F78811;">]</span><span style="color: #F78811;">(</span>some<span style="color: #000080;">:</span> A <span style="color: #000080;">=&gt;</span> X, none<span style="color: #000080;">:</span> <span style="color: #000080;">=&gt;</span> X<span style="color: #F78811;">)</span> <span style="color: #000080;">=</span> none
  <span style="color: #F78811;">}</span>
 
  <span style="color: #008000; font-style: italic;">// Done for you</span>
  <span style="color: #0000ff; font-weight: bold;">def</span> some<span style="color: #F78811;">[</span>A<span style="color: #F78811;">]</span><span style="color: #F78811;">(</span>a<span style="color: #000080;">:</span> A<span style="color: #F78811;">)</span><span style="color: #000080;">:</span> Optional<span style="color: #F78811;">[</span>A<span style="color: #F78811;">]</span> <span style="color: #000080;">=</span> <span style="color: #0000ff; font-weight: bold;">new</span> Optional<span style="color: #F78811;">[</span>A<span style="color: #F78811;">]</span> <span style="color: #F78811;">{</span>
    <span style="color: #0000ff; font-weight: bold;">def</span> fold<span style="color: #F78811;">[</span>X<span style="color: #F78811;">]</span><span style="color: #F78811;">(</span>some<span style="color: #000080;">:</span> A <span style="color: #000080;">=&gt;</span> X, none<span style="color: #000080;">:</span> <span style="color: #000080;">=&gt;</span> X<span style="color: #F78811;">)</span> <span style="color: #000080;">=</span> some<span style="color: #F78811;">(</span>a<span style="color: #F78811;">)</span>
  <span style="color: #F78811;">}</span>
 
  <span style="color: #008000; font-style: italic;">// Utility</span>
  <span style="color: #0000ff; font-weight: bold;">def</span> fromOption<span style="color: #F78811;">[</span>A<span style="color: #F78811;">]</span><span style="color: #F78811;">(</span>o<span style="color: #000080;">:</span> Option<span style="color: #F78811;">[</span>A<span style="color: #F78811;">]</span><span style="color: #F78811;">)</span><span style="color: #000080;">:</span> Optional<span style="color: #F78811;">[</span>A<span style="color: #F78811;">]</span> <span style="color: #000080;">=</span> o <span style="color: #0000ff; font-weight: bold;">match</span> <span style="color: #F78811;">{</span>
    <span style="color: #0000ff; font-weight: bold;">case</span> None    <span style="color: #000080;">=&gt;</span> none
    <span style="color: #0000ff; font-weight: bold;">case</span> Some<span style="color: #F78811;">(</span>a<span style="color: #F78811;">)</span> <span style="color: #000080;">=&gt;</span> some<span style="color: #F78811;">(</span>a<span style="color: #F78811;">)</span>
  <span style="color: #F78811;">}</span>
 
  <span style="color: #008000; font-style: italic;">// *** Special note ***</span>
  <span style="color: #008000; font-style: italic;">// Some of these functions are likely to be familiar List functions,</span>
  <span style="color: #008000; font-style: italic;">// but with one specific distinction: in every covariant value appearing in</span>
  <span style="color: #008000; font-style: italic;">// the type signature, this value is wrapped in Optional.</span>
  <span style="color: #008000; font-style: italic;">// For example, the unwrapped:</span>
  <span style="color: #008000; font-style: italic;">// filter:          (A =&gt; Boolean) =&gt; List[A] =&gt; List[A]</span>
  <span style="color: #008000; font-style: italic;">// and the wrapped:</span>
  <span style="color: #008000; font-style: italic;">// filterOptionals: (A =&gt; Optional[Boolean]) =&gt; List[A] =&gt; Optional[List[A]]</span>
  <span style="color: #008000; font-style: italic;">// </span>
  <span style="color: #008000; font-style: italic;">// There are other functions of a similar nature below.</span>
 
  <span style="color: #008000; font-style: italic;">// Exercise 16</span>
  <span style="color: #008000; font-style: italic;">// If a none is encountered, then return a none, otherwise,</span>
  <span style="color: #008000; font-style: italic;">// accumulate all the values in Optional.</span>
  <span style="color: #0000ff; font-weight: bold;">def</span> mapOptionals<span style="color: #F78811;">[</span>A, B<span style="color: #F78811;">]</span><span style="color: #F78811;">(</span>f<span style="color: #000080;">:</span> A <span style="color: #000080;">=&gt;</span> Optional<span style="color: #F78811;">[</span>B<span style="color: #F78811;">]</span>, a<span style="color: #000080;">:</span> List<span style="color: #F78811;">[</span>A<span style="color: #F78811;">]</span><span style="color: #F78811;">)</span><span style="color: #000080;">:</span> Optional<span style="color: #F78811;">[</span>List<span style="color: #F78811;">[</span>B<span style="color: #F78811;">]</span><span style="color: #F78811;">]</span> <span style="color: #000080;">=</span>
    error<span style="color: #F78811;">(</span><span style="color: #6666FF;">"todo"</span><span style="color: #F78811;">)</span>
 
  <span style="color: #008000; font-style: italic;">// Exercise 17</span>
  <span style="color: #008000; font-style: italic;">// If a none is encountered, then return a none, otherwise,</span>
  <span style="color: #008000; font-style: italic;">// accumulate all the values in Optional.</span>
  <span style="color: #0000ff; font-weight: bold;">def</span> sequenceOptionals<span style="color: #F78811;">[</span>A<span style="color: #F78811;">]</span><span style="color: #F78811;">(</span>a<span style="color: #000080;">:</span> List<span style="color: #F78811;">[</span>Optional<span style="color: #F78811;">[</span>A<span style="color: #F78811;">]</span><span style="color: #F78811;">]</span><span style="color: #F78811;">)</span><span style="color: #000080;">:</span> Optional<span style="color: #F78811;">[</span>List<span style="color: #F78811;">[</span>A<span style="color: #F78811;">]</span><span style="color: #F78811;">]</span> <span style="color: #000080;">=</span>
    error<span style="color: #F78811;">(</span><span style="color: #6666FF;">"todo"</span><span style="color: #F78811;">)</span>
 
  <span style="color: #008000; font-style: italic;">// Exercise 18</span>
  <span style="color: #008000; font-style: italic;">// Use sequenceOptionals</span>
  <span style="color: #0000ff; font-weight: bold;">def</span> mapOptionalsAgain<span style="color: #F78811;">[</span>A, B<span style="color: #F78811;">]</span><span style="color: #F78811;">(</span>f<span style="color: #000080;">:</span> A <span style="color: #000080;">=&gt;</span> Optional<span style="color: #F78811;">[</span>B<span style="color: #F78811;">]</span>, a<span style="color: #000080;">:</span> List<span style="color: #F78811;">[</span>A<span style="color: #F78811;">]</span><span style="color: #F78811;">)</span><span style="color: #000080;">:</span> Optional<span style="color: #F78811;">[</span>List<span style="color: #F78811;">[</span>B<span style="color: #F78811;">]</span><span style="color: #F78811;">]</span> <span style="color: #000080;">=</span>
    error<span style="color: #F78811;">(</span><span style="color: #6666FF;">"todo"</span><span style="color: #F78811;">)</span>
 
  <span style="color: #008000; font-style: italic;">// Exercise 19 </span>
  <span style="color: #008000; font-style: italic;">// Use mapOptionals</span>
  <span style="color: #0000ff; font-weight: bold;">def</span> sequenceOptionalsAgain<span style="color: #F78811;">[</span>A<span style="color: #F78811;">]</span><span style="color: #F78811;">(</span>a<span style="color: #000080;">:</span> List<span style="color: #F78811;">[</span>Optional<span style="color: #F78811;">[</span>A<span style="color: #F78811;">]</span><span style="color: #F78811;">]</span><span style="color: #F78811;">)</span><span style="color: #000080;">:</span> Optional<span style="color: #F78811;">[</span>List<span style="color: #F78811;">[</span>A<span style="color: #F78811;">]</span><span style="color: #F78811;">]</span> <span style="color: #000080;">=</span>
    error<span style="color: #F78811;">(</span><span style="color: #6666FF;">"todo"</span><span style="color: #F78811;">)</span>
 
  <span style="color: #008000; font-style: italic;">// Exercise 20</span>
  <span style="color: #008000; font-style: italic;">// If a none is encountered, return none, otherwise,</span>
  <span style="color: #008000; font-style: italic;">// flatten/join by one level.</span>
  <span style="color: #0000ff; font-weight: bold;">def</span> joinOptionals<span style="color: #F78811;">[</span>A<span style="color: #F78811;">]</span><span style="color: #F78811;">(</span>a<span style="color: #000080;">:</span> Optional<span style="color: #F78811;">[</span>Optional<span style="color: #F78811;">[</span>A<span style="color: #F78811;">]</span><span style="color: #F78811;">]</span><span style="color: #F78811;">)</span><span style="color: #000080;">:</span> Optional<span style="color: #F78811;">[</span>A<span style="color: #F78811;">]</span> <span style="color: #000080;">=</span>
    error<span style="color: #F78811;">(</span><span style="color: #6666FF;">"todo"</span><span style="color: #F78811;">)</span>
 
  <span style="color: #008000; font-style: italic;">// Exercise 21</span>
  <span style="color: #0000ff; font-weight: bold;">def</span> filterOptionals<span style="color: #F78811;">[</span>A<span style="color: #F78811;">]</span><span style="color: #F78811;">(</span>p<span style="color: #000080;">:</span> A <span style="color: #000080;">=&gt;</span> Optional<span style="color: #F78811;">[</span><span style="color: #9999cc; font-weight: bold;">Boolean</span><span style="color: #F78811;">]</span>, a<span style="color: #000080;">:</span> List<span style="color: #F78811;">[</span>A<span style="color: #F78811;">]</span><span style="color: #F78811;">)</span><span style="color: #000080;">:</span> Optional<span style="color: #F78811;">[</span>List<span style="color: #F78811;">[</span>A<span style="color: #F78811;">]</span><span style="color: #F78811;">]</span> <span style="color: #000080;">=</span>
    error<span style="color: #F78811;">(</span><span style="color: #6666FF;">"todo"</span><span style="color: #F78811;">)</span>
 
  <span style="color: #008000; font-style: italic;">// Exercise 22</span>
  <span style="color: #0000ff; font-weight: bold;">def</span> fillOptionals<span style="color: #F78811;">[</span>A<span style="color: #F78811;">]</span><span style="color: #F78811;">(</span>n<span style="color: #000080;">:</span> <span style="color: #9999cc; font-weight: bold;">Int</span>, a<span style="color: #000080;">:</span> Optional<span style="color: #F78811;">[</span>A<span style="color: #F78811;">]</span><span style="color: #F78811;">)</span><span style="color: #000080;">:</span> Optional<span style="color: #F78811;">[</span>List<span style="color: #F78811;">[</span>A<span style="color: #F78811;">]</span><span style="color: #F78811;">]</span> <span style="color: #000080;">=</span>
    error<span style="color: #F78811;">(</span><span style="color: #6666FF;">"todo"</span><span style="color: #F78811;">)</span>
 
  <span style="color: #008000; font-style: italic;">// Exercise 23</span>
  <span style="color: #008000; font-style: italic;">// Use sequenceOptionals</span>
  <span style="color: #0000ff; font-weight: bold;">def</span> fillOptionalsAgain<span style="color: #F78811;">[</span>A<span style="color: #F78811;">]</span><span style="color: #F78811;">(</span>n<span style="color: #000080;">:</span> <span style="color: #9999cc; font-weight: bold;">Int</span>, a<span style="color: #000080;">:</span> Optional<span style="color: #F78811;">[</span>A<span style="color: #F78811;">]</span><span style="color: #F78811;">)</span><span style="color: #000080;">:</span> Optional<span style="color: #F78811;">[</span>List<span style="color: #F78811;">[</span>A<span style="color: #F78811;">]</span><span style="color: #F78811;">]</span> <span style="color: #000080;">=</span>
    error<span style="color: #F78811;">(</span><span style="color: #6666FF;">"todo"</span><span style="color: #F78811;">)</span>
 
  <span style="color: #008000; font-style: italic;">// Exercise 24</span>
  <span style="color: #008000; font-style: italic;">// Methods mentioning Optional in the type signature are prohibited, except applic and map</span>
  <span style="color: #0000ff; font-weight: bold;">def</span> mapOptionalsYetAgain<span style="color: #F78811;">[</span>A, B<span style="color: #F78811;">]</span><span style="color: #F78811;">(</span>f<span style="color: #000080;">:</span> A <span style="color: #000080;">=&gt;</span> Optional<span style="color: #F78811;">[</span>B<span style="color: #F78811;">]</span>, a<span style="color: #000080;">:</span> List<span style="color: #F78811;">[</span>A<span style="color: #F78811;">]</span><span style="color: #F78811;">)</span><span style="color: #000080;">:</span> Optional<span style="color: #F78811;">[</span>List<span style="color: #F78811;">[</span>B<span style="color: #F78811;">]</span><span style="color: #F78811;">]</span> <span style="color: #000080;">=</span>
    error<span style="color: #F78811;">(</span><span style="color: #6666FF;">"todo"</span><span style="color: #F78811;">)</span>
 
  <span style="color: #008000; font-style: italic;">// Consider: def joinOptional[A](a: Optional[Optional[A]]): Optional[A]</span>
  <span style="color: #008000; font-style: italic;">// This function "flattens" the Optional into a Some value if possible.</span>
  <span style="color: #008000; font-style: italic;">// It is not possible to write this using only applic and map (try it!).</span>
 
  <span style="color: #008000; font-style: italic;">// Bye bye Option-specificity!</span>
  <span style="color: #008000; font-style: italic;">// (setting up for Exercise 25)</span>
  <span style="color: #0000ff; font-weight: bold;">trait</span> Applic<span style="color: #F78811;">[</span>F<span style="color: #F78811;">[</span><span style="color: #000080;">_</span><span style="color: #F78811;">]</span><span style="color: #F78811;">]</span> <span style="color: #F78811;">{</span>
    <span style="color: #0000ff; font-weight: bold;">def</span> point<span style="color: #F78811;">[</span>A<span style="color: #F78811;">]</span><span style="color: #F78811;">(</span>a<span style="color: #000080;">:</span> A<span style="color: #F78811;">)</span><span style="color: #000080;">:</span> F<span style="color: #F78811;">[</span>A<span style="color: #F78811;">]</span>
    <span style="color: #0000ff; font-weight: bold;">def</span> applic<span style="color: #F78811;">[</span>A, B<span style="color: #F78811;">]</span><span style="color: #F78811;">(</span>f<span style="color: #000080;">:</span> F<span style="color: #F78811;">[</span>A <span style="color: #000080;">=&gt;</span> B<span style="color: #F78811;">]</span>, a<span style="color: #000080;">:</span> F<span style="color: #F78811;">[</span>A<span style="color: #F78811;">]</span><span style="color: #F78811;">)</span><span style="color: #000080;">:</span> F<span style="color: #F78811;">[</span>B<span style="color: #F78811;">]</span>
 
    <span style="color: #0000ff; font-weight: bold;">final</span> <span style="color: #0000ff; font-weight: bold;">def</span> map<span style="color: #F78811;">[</span>A, B<span style="color: #F78811;">]</span><span style="color: #F78811;">(</span>f<span style="color: #000080;">:</span> A <span style="color: #000080;">=&gt;</span> B, a<span style="color: #000080;">:</span> F<span style="color: #F78811;">[</span>A<span style="color: #F78811;">]</span><span style="color: #F78811;">)</span><span style="color: #000080;">:</span> F<span style="color: #F78811;">[</span>B<span style="color: #F78811;">]</span> <span style="color: #000080;">=</span>
      applic<span style="color: #F78811;">(</span>point<span style="color: #F78811;">(</span>f<span style="color: #F78811;">)</span>, a<span style="color: #F78811;">)</span>
  <span style="color: #F78811;">}</span>
 
  <span style="color: #0000ff; font-weight: bold;">object</span> Applic <span style="color: #F78811;">{</span>
    <span style="color: #0000ff; font-weight: bold;">implicit</span> <span style="color: #0000ff; font-weight: bold;">val</span> OptionalApplic<span style="color: #000080;">:</span> Applic<span style="color: #F78811;">[</span>Optional<span style="color: #F78811;">]</span> <span style="color: #000080;">=</span> <span style="color: #0000ff; font-weight: bold;">new</span> Applic<span style="color: #F78811;">[</span>Optional<span style="color: #F78811;">]</span> <span style="color: #F78811;">{</span>
      <span style="color: #0000ff; font-weight: bold;">def</span> point<span style="color: #F78811;">[</span>A<span style="color: #F78811;">]</span><span style="color: #F78811;">(</span>a<span style="color: #000080;">:</span> A<span style="color: #F78811;">)</span><span style="color: #000080;">:</span> Optional<span style="color: #F78811;">[</span>A<span style="color: #F78811;">]</span> <span style="color: #000080;">=</span> some<span style="color: #F78811;">(</span>a<span style="color: #F78811;">)</span>
      <span style="color: #0000ff; font-weight: bold;">def</span> applic<span style="color: #F78811;">[</span>A, B<span style="color: #F78811;">]</span><span style="color: #F78811;">(</span>f<span style="color: #000080;">:</span> Optional<span style="color: #F78811;">[</span>A <span style="color: #000080;">=&gt;</span> B<span style="color: #F78811;">]</span>, a<span style="color: #000080;">:</span> Optional<span style="color: #F78811;">[</span>A<span style="color: #F78811;">]</span><span style="color: #F78811;">)</span><span style="color: #000080;">:</span> Optional<span style="color: #F78811;">[</span>B<span style="color: #F78811;">]</span> <span style="color: #000080;">=</span> a applic f
    <span style="color: #F78811;">}</span>
  <span style="color: #F78811;">}</span>
 
  <span style="color: #008000; font-style: italic;">// Exercise 25</span>
  <span style="color: #008000; font-style: italic;">// The Double-Clincher!</span>
  <span style="color: #0000ff; font-weight: bold;">def</span> mapWhatever<span style="color: #F78811;">[</span>A, B, F<span style="color: #F78811;">[</span><span style="color: #000080;">_</span><span style="color: #F78811;">]</span><span style="color: #F78811;">]</span><span style="color: #F78811;">(</span>f<span style="color: #000080;">:</span> A <span style="color: #000080;">=&gt;</span> F<span style="color: #F78811;">[</span>B<span style="color: #F78811;">]</span>, a<span style="color: #000080;">:</span> List<span style="color: #F78811;">[</span>A<span style="color: #F78811;">]</span><span style="color: #F78811;">)</span><span style="color: #F78811;">(</span><span style="color: #0000ff; font-weight: bold;">implicit</span> z<span style="color: #000080;">:</span> Applic<span style="color: #F78811;">[</span>F<span style="color: #F78811;">]</span><span style="color: #F78811;">)</span><span style="color: #000080;">:</span> F<span style="color: #F78811;">[</span>List<span style="color: #F78811;">[</span>B<span style="color: #F78811;">]</span><span style="color: #F78811;">]</span> <span style="color: #000080;">=</span>
    error<span style="color: #F78811;">(</span><span style="color: #6666FF;">"todo"</span><span style="color: #F78811;">)</span>
<span style="color: #F78811;">}</span>
 
<span style="color: #0000ff; font-weight: bold;">import</span> org.<span style="color: #000000;">scalacheck</span>.<span style="color: #000080;">_</span>
<span style="color: #0000ff; font-weight: bold;">import</span> Arbitrary.<span style="color: #000000;">arbitrary</span>
<span style="color: #0000ff; font-weight: bold;">import</span> Prop.<span style="color: #000080;">_</span>
 
<span style="color: #0000ff; font-weight: bold;">object</span> TestOptional <span style="color: #0000ff; font-weight: bold;">extends</span> Properties<span style="color: #F78811;">(</span><span style="color: #6666FF;">"Optional"</span><span style="color: #F78811;">)</span> <span style="color: #F78811;">{</span>
  <span style="color: #0000ff; font-weight: bold;">import</span> Optional.<span style="color: #000080;">_</span>
 
  <span style="color: #0000ff; font-weight: bold;">implicit</span> <span style="color: #0000ff; font-weight: bold;">def</span> ArbitraryOptional<span style="color: #F78811;">[</span>A<span style="color: #F78811;">]</span><span style="color: #F78811;">(</span><span style="color: #0000ff; font-weight: bold;">implicit</span> a<span style="color: #000080;">:</span> Arbitrary<span style="color: #F78811;">[</span>A<span style="color: #F78811;">]</span><span style="color: #F78811;">)</span><span style="color: #000080;">:</span> Arbitrary<span style="color: #F78811;">[</span>Optional<span style="color: #F78811;">[</span>A<span style="color: #F78811;">]</span><span style="color: #F78811;">]</span> <span style="color: #000080;">=</span>
    Arbitrary<span style="color: #F78811;">(</span>arbitrary<span style="color: #F78811;">[</span>Option<span style="color: #F78811;">[</span>A<span style="color: #F78811;">]</span><span style="color: #F78811;">]</span> map fromOption<span style="color: #F78811;">)</span>
 
  property<span style="color: #F78811;">(</span><span style="color: #6666FF;">"map"</span><span style="color: #F78811;">)</span> <span style="color: #000080;">=</span> forAll <span style="color: #F78811;">(</span><span style="color: #F78811;">(</span>o<span style="color: #000080;">:</span> Optional<span style="color: #F78811;">[</span><span style="color: #9999cc; font-weight: bold;">Int</span><span style="color: #F78811;">]</span>, f<span style="color: #000080;">:</span> <span style="color: #9999cc; font-weight: bold;">Int</span> <span style="color: #000080;">=&gt;</span> String<span style="color: #F78811;">)</span> <span style="color: #000080;">=&gt;</span>
    <span style="color: #F78811;">(</span>o map f<span style="color: #F78811;">)</span>.<span style="color: #000000;">toOption</span> <span style="color: #000080;">==</span> <span style="color: #F78811;">(</span>o.<span style="color: #000000;">toOption</span> map f<span style="color: #F78811;">)</span><span style="color: #F78811;">)</span>
 
  property<span style="color: #F78811;">(</span><span style="color: #6666FF;">"get"</span><span style="color: #F78811;">)</span> <span style="color: #000080;">=</span> forAll<span style="color: #F78811;">(</span><span style="color: #F78811;">(</span>o<span style="color: #000080;">:</span> Optional<span style="color: #F78811;">[</span><span style="color: #9999cc; font-weight: bold;">Int</span><span style="color: #F78811;">]</span><span style="color: #F78811;">)</span> <span style="color: #000080;">=&gt;</span>
    o.<span style="color: #000000;">isDefined</span> <span style="color: #000080;">==&gt;</span>
      <span style="color: #F78811;">(</span>o.<span style="color: #000000;">get</span> <span style="color: #000080;">==</span> o.<span style="color: #000000;">toOption</span>.<span style="color: #000000;">get</span><span style="color: #F78811;">)</span><span style="color: #F78811;">)</span>
 
  property<span style="color: #F78811;">(</span><span style="color: #6666FF;">"flatMap"</span><span style="color: #F78811;">)</span> <span style="color: #000080;">=</span> forAll<span style="color: #F78811;">(</span><span style="color: #F78811;">(</span>o<span style="color: #000080;">:</span> Optional<span style="color: #F78811;">[</span><span style="color: #9999cc; font-weight: bold;">Int</span><span style="color: #F78811;">]</span>, f<span style="color: #000080;">:</span> <span style="color: #9999cc; font-weight: bold;">Int</span> <span style="color: #000080;">=&gt;</span> Optional<span style="color: #F78811;">[</span>String<span style="color: #F78811;">]</span><span style="color: #F78811;">)</span> <span style="color: #000080;">=&gt;</span>
    <span style="color: #F78811;">(</span>o flatMap f<span style="color: #F78811;">)</span>.<span style="color: #000000;">toOption</span> <span style="color: #000080;">==</span> <span style="color: #F78811;">(</span>o.<span style="color: #000000;">toOption</span> flatMap <span style="color: #F78811;">(</span>f<span style="color: #F78811;">(</span><span style="color: #000080;">_</span><span style="color: #F78811;">)</span>.<span style="color: #000000;">toOption</span><span style="color: #F78811;">)</span><span style="color: #F78811;">)</span><span style="color: #F78811;">)</span>
 
  property<span style="color: #F78811;">(</span><span style="color: #6666FF;">"mapAgain"</span><span style="color: #F78811;">)</span> <span style="color: #000080;">=</span> forAll <span style="color: #F78811;">(</span><span style="color: #F78811;">(</span>o<span style="color: #000080;">:</span> Optional<span style="color: #F78811;">[</span><span style="color: #9999cc; font-weight: bold;">Int</span><span style="color: #F78811;">]</span>, f<span style="color: #000080;">:</span> <span style="color: #9999cc; font-weight: bold;">Int</span> <span style="color: #000080;">=&gt;</span> String<span style="color: #F78811;">)</span> <span style="color: #000080;">=&gt;</span>
    <span style="color: #F78811;">(</span>o mapAgain f<span style="color: #F78811;">)</span>.<span style="color: #000000;">toOption</span> <span style="color: #000080;">==</span> <span style="color: #F78811;">(</span>o map f<span style="color: #F78811;">)</span>.<span style="color: #000000;">toOption</span><span style="color: #F78811;">)</span>
 
  property<span style="color: #F78811;">(</span><span style="color: #6666FF;">"getOrElse"</span><span style="color: #F78811;">)</span> <span style="color: #000080;">=</span> forAll <span style="color: #F78811;">(</span><span style="color: #F78811;">(</span>o<span style="color: #000080;">:</span> Optional<span style="color: #F78811;">[</span><span style="color: #9999cc; font-weight: bold;">Int</span><span style="color: #F78811;">]</span>, n<span style="color: #000080;">:</span> <span style="color: #9999cc; font-weight: bold;">Int</span><span style="color: #F78811;">)</span> <span style="color: #000080;">=&gt;</span>
    <span style="color: #F78811;">(</span>o getOrElse n<span style="color: #F78811;">)</span> <span style="color: #000080;">==</span> <span style="color: #F78811;">(</span>o.<span style="color: #000000;">toOption</span> getOrElse n<span style="color: #F78811;">)</span><span style="color: #F78811;">)</span>
 
  property<span style="color: #F78811;">(</span><span style="color: #6666FF;">"filter"</span><span style="color: #F78811;">)</span> <span style="color: #000080;">=</span> forAll <span style="color: #F78811;">(</span><span style="color: #F78811;">(</span>o<span style="color: #000080;">:</span> Optional<span style="color: #F78811;">[</span><span style="color: #9999cc; font-weight: bold;">Int</span><span style="color: #F78811;">]</span>, f<span style="color: #000080;">:</span> <span style="color: #9999cc; font-weight: bold;">Int</span> <span style="color: #000080;">=&gt;</span> <span style="color: #9999cc; font-weight: bold;">Boolean</span><span style="color: #F78811;">)</span> <span style="color: #000080;">=&gt;</span>
    <span style="color: #F78811;">(</span>o filter f<span style="color: #F78811;">)</span>.<span style="color: #000000;">toOption</span> <span style="color: #000080;">==</span> <span style="color: #F78811;">(</span>o.<span style="color: #000000;">toOption</span> filter f<span style="color: #F78811;">)</span><span style="color: #F78811;">)</span>
 
  property<span style="color: #F78811;">(</span><span style="color: #6666FF;">"exists"</span><span style="color: #F78811;">)</span> <span style="color: #000080;">=</span> forAll <span style="color: #F78811;">(</span><span style="color: #F78811;">(</span>o<span style="color: #000080;">:</span> Optional<span style="color: #F78811;">[</span><span style="color: #9999cc; font-weight: bold;">Int</span><span style="color: #F78811;">]</span>, f<span style="color: #000080;">:</span> <span style="color: #9999cc; font-weight: bold;">Int</span> <span style="color: #000080;">=&gt;</span> <span style="color: #9999cc; font-weight: bold;">Boolean</span><span style="color: #F78811;">)</span> <span style="color: #000080;">=&gt;</span>
    <span style="color: #F78811;">(</span>o exists f<span style="color: #F78811;">)</span> <span style="color: #000080;">==</span> <span style="color: #F78811;">(</span>o.<span style="color: #000000;">toOption</span> exists f<span style="color: #F78811;">)</span><span style="color: #F78811;">)</span>
 
  property<span style="color: #F78811;">(</span><span style="color: #6666FF;">"forall"</span><span style="color: #F78811;">)</span> <span style="color: #000080;">=</span> forAll <span style="color: #F78811;">(</span><span style="color: #F78811;">(</span>o<span style="color: #000080;">:</span> Optional<span style="color: #F78811;">[</span><span style="color: #9999cc; font-weight: bold;">Int</span><span style="color: #F78811;">]</span>, f<span style="color: #000080;">:</span> <span style="color: #9999cc; font-weight: bold;">Int</span> <span style="color: #000080;">=&gt;</span> <span style="color: #9999cc; font-weight: bold;">Boolean</span><span style="color: #F78811;">)</span> <span style="color: #000080;">=&gt;</span>
    <span style="color: #F78811;">(</span>o forall f<span style="color: #F78811;">)</span> <span style="color: #000080;">==</span> <span style="color: #F78811;">(</span>o.<span style="color: #000000;">toOption</span> forall f<span style="color: #F78811;">)</span><span style="color: #F78811;">)</span>
 
  property<span style="color: #F78811;">(</span><span style="color: #6666FF;">"foreach"</span><span style="color: #F78811;">)</span> <span style="color: #000080;">=</span> forAll <span style="color: #F78811;">(</span><span style="color: #F78811;">(</span>o<span style="color: #000080;">:</span> Optional<span style="color: #F78811;">[</span><span style="color: #9999cc; font-weight: bold;">Int</span><span style="color: #F78811;">]</span>, f<span style="color: #000080;">:</span> <span style="color: #9999cc; font-weight: bold;">Int</span> <span style="color: #000080;">=&gt;</span> Unit, n<span style="color: #000080;">:</span> <span style="color: #9999cc; font-weight: bold;">Int</span><span style="color: #F78811;">)</span> <span style="color: #000080;">=&gt;</span> <span style="color: #F78811;">{</span>
    <span style="color: #0000ff; font-weight: bold;">var</span> x<span style="color: #000080;">:</span> <span style="color: #9999cc; font-weight: bold;">Int</span> <span style="color: #000080;">=</span> n
    <span style="color: #0000ff; font-weight: bold;">var</span> y<span style="color: #000080;">:</span> <span style="color: #9999cc; font-weight: bold;">Int</span> <span style="color: #000080;">=</span> x
 
    o foreach <span style="color: #F78811;">(</span>t <span style="color: #000080;">=&gt;</span> x <span style="color: #000080;">=</span> x + t<span style="color: #F78811;">)</span>
    o.<span style="color: #000000;">toOption</span> foreach <span style="color: #F78811;">(</span>t <span style="color: #000080;">=&gt;</span> y <span style="color: #000080;">=</span> y + t<span style="color: #F78811;">)</span>
 
    x <span style="color: #000080;">==</span> y
  <span style="color: #F78811;">}</span><span style="color: #F78811;">)</span>
 
  property<span style="color: #F78811;">(</span><span style="color: #6666FF;">"isDefined"</span><span style="color: #F78811;">)</span> <span style="color: #000080;">=</span> forAll <span style="color: #F78811;">(</span><span style="color: #F78811;">(</span>o<span style="color: #000080;">:</span> Optional<span style="color: #F78811;">[</span><span style="color: #9999cc; font-weight: bold;">Int</span><span style="color: #F78811;">]</span><span style="color: #F78811;">)</span> <span style="color: #000080;">=&gt;</span>
    <span style="color: #F78811;">(</span>o.<span style="color: #000000;">isDefined</span><span style="color: #F78811;">)</span> <span style="color: #000080;">==</span> <span style="color: #F78811;">(</span>o.<span style="color: #000000;">toOption</span>.<span style="color: #000000;">isDefined</span><span style="color: #F78811;">)</span><span style="color: #F78811;">)</span>
 
  property<span style="color: #F78811;">(</span><span style="color: #6666FF;">"isEmpty"</span><span style="color: #F78811;">)</span> <span style="color: #000080;">=</span> forAll <span style="color: #F78811;">(</span><span style="color: #F78811;">(</span>o<span style="color: #000080;">:</span> Optional<span style="color: #F78811;">[</span><span style="color: #9999cc; font-weight: bold;">Int</span><span style="color: #F78811;">]</span><span style="color: #F78811;">)</span> <span style="color: #000080;">=&gt;</span>
    o.<span style="color: #000000;">isEmpty</span> <span style="color: #000080;">==</span> o.<span style="color: #000000;">toOption</span>.<span style="color: #000000;">isEmpty</span><span style="color: #F78811;">)</span>
 
  property<span style="color: #F78811;">(</span><span style="color: #6666FF;">"orElse"</span><span style="color: #F78811;">)</span> <span style="color: #000080;">=</span> forAll <span style="color: #F78811;">(</span><span style="color: #F78811;">(</span>o<span style="color: #000080;">:</span> Optional<span style="color: #F78811;">[</span><span style="color: #9999cc; font-weight: bold;">Int</span><span style="color: #F78811;">]</span>, p<span style="color: #000080;">:</span> Optional<span style="color: #F78811;">[</span><span style="color: #9999cc; font-weight: bold;">Int</span><span style="color: #F78811;">]</span><span style="color: #F78811;">)</span> <span style="color: #000080;">=&gt;</span>
    <span style="color: #F78811;">(</span>o orElse p<span style="color: #F78811;">)</span>.<span style="color: #000000;">toOption</span> <span style="color: #000080;">==</span> <span style="color: #F78811;">(</span>o.<span style="color: #000000;">toOption</span> orElse p.<span style="color: #000000;">toOption</span><span style="color: #F78811;">)</span><span style="color: #F78811;">)</span>
 
  property<span style="color: #F78811;">(</span><span style="color: #6666FF;">"toLeft"</span><span style="color: #F78811;">)</span> <span style="color: #000080;">=</span> forAll <span style="color: #F78811;">(</span><span style="color: #F78811;">(</span>o<span style="color: #000080;">:</span> Optional<span style="color: #F78811;">[</span><span style="color: #9999cc; font-weight: bold;">Int</span><span style="color: #F78811;">]</span>, n<span style="color: #000080;">:</span> <span style="color: #9999cc; font-weight: bold;">Int</span><span style="color: #F78811;">)</span> <span style="color: #000080;">=&gt;</span>
    <span style="color: #F78811;">(</span>o toLeft n<span style="color: #F78811;">)</span> <span style="color: #000080;">==</span> <span style="color: #F78811;">(</span>o.<span style="color: #000000;">toOption</span> toLeft n<span style="color: #F78811;">)</span><span style="color: #F78811;">)</span>
 
  property<span style="color: #F78811;">(</span><span style="color: #6666FF;">"toRight"</span><span style="color: #F78811;">)</span> <span style="color: #000080;">=</span> forAll <span style="color: #F78811;">(</span><span style="color: #F78811;">(</span>o<span style="color: #000080;">:</span> Optional<span style="color: #F78811;">[</span><span style="color: #9999cc; font-weight: bold;">Int</span><span style="color: #F78811;">]</span>, n<span style="color: #000080;">:</span> <span style="color: #9999cc; font-weight: bold;">Int</span><span style="color: #F78811;">)</span> <span style="color: #000080;">=&gt;</span>
    <span style="color: #F78811;">(</span>o toRight n<span style="color: #F78811;">)</span> <span style="color: #000080;">==</span> <span style="color: #F78811;">(</span>o.<span style="color: #000000;">toOption</span> toRight n<span style="color: #F78811;">)</span><span style="color: #F78811;">)</span>
 
  property<span style="color: #F78811;">(</span><span style="color: #6666FF;">"toList"</span><span style="color: #F78811;">)</span> <span style="color: #000080;">=</span> forAll <span style="color: #F78811;">(</span><span style="color: #F78811;">(</span>o<span style="color: #000080;">:</span> Optional<span style="color: #F78811;">[</span><span style="color: #9999cc; font-weight: bold;">Int</span><span style="color: #F78811;">]</span><span style="color: #F78811;">)</span> <span style="color: #000080;">=&gt;</span>
    o.<span style="color: #000000;">toList</span> <span style="color: #000080;">==</span> o.<span style="color: #000000;">toOption</span>.<span style="color: #000000;">toList</span><span style="color: #F78811;">)</span>
 
  property<span style="color: #F78811;">(</span><span style="color: #6666FF;">"iterator"</span><span style="color: #F78811;">)</span> <span style="color: #000080;">=</span> forAll <span style="color: #F78811;">(</span><span style="color: #F78811;">(</span>o<span style="color: #000080;">:</span> Optional<span style="color: #F78811;">[</span><span style="color: #9999cc; font-weight: bold;">Int</span><span style="color: #F78811;">]</span><span style="color: #F78811;">)</span> <span style="color: #000080;">=&gt;</span>
    o.<span style="color: #000000;">iterator</span> sameElements o.<span style="color: #000000;">toOption</span>.<span style="color: #000000;">iterator</span><span style="color: #F78811;">)</span>
 
  <span style="color: #008000; font-style: italic;">// *** READ THIS COMMENT FIRST ***</span>
  <span style="color: #008000; font-style: italic;">// Note that scala.Option has no such equivalent to this method</span>
  <span style="color: #008000; font-style: italic;">// Therefore, reading this test may give away clues to how it might be solved.</span>
  <span style="color: #008000; font-style: italic;">// If you do not wish to spoil it, look away now and follow the</span>
  <span style="color: #008000; font-style: italic;">// instruction in the Exercise comment.</span>
  property<span style="color: #F78811;">(</span><span style="color: #6666FF;">"applic"</span><span style="color: #F78811;">)</span> <span style="color: #000080;">=</span> forAll <span style="color: #F78811;">(</span><span style="color: #F78811;">(</span>o<span style="color: #000080;">:</span> Optional<span style="color: #F78811;">[</span><span style="color: #9999cc; font-weight: bold;">Int</span> <span style="color: #000080;">=&gt;</span> String<span style="color: #F78811;">]</span>, p<span style="color: #000080;">:</span> Optional<span style="color: #F78811;">[</span><span style="color: #9999cc; font-weight: bold;">Int</span><span style="color: #F78811;">]</span><span style="color: #F78811;">)</span> <span style="color: #000080;">=&gt;</span>
    <span style="color: #F78811;">(</span>p applic o<span style="color: #F78811;">)</span>.<span style="color: #000000;">toOption</span> <span style="color: #000080;">==</span>
    <span style="color: #F78811;">(</span><span style="color: #0000ff; font-weight: bold;">for</span><span style="color: #F78811;">(</span>f <span style="color: #000080;">&lt;</span>- o.<span style="color: #000000;">toOption</span><span style="color: #000080;">;</span>
         n <span style="color: #000080;">&lt;</span>- p.<span style="color: #000000;">toOption</span><span style="color: #F78811;">)</span>
    <span style="color: #0000ff; font-weight: bold;">yield</span> f<span style="color: #F78811;">(</span>n<span style="color: #F78811;">)</span><span style="color: #F78811;">)</span><span style="color: #F78811;">)</span>
 
  <span style="color: #0000ff; font-weight: bold;">def</span> trace<span style="color: #F78811;">[</span>A<span style="color: #F78811;">]</span><span style="color: #F78811;">(</span>a<span style="color: #000080;">:</span> A<span style="color: #F78811;">)</span> <span style="color: #000080;">=</span> <span style="color: #F78811;">{</span>
    println<span style="color: #F78811;">(</span>a<span style="color: #F78811;">)</span>
    a
  <span style="color: #F78811;">}</span>
 
  property<span style="color: #F78811;">(</span><span style="color: #6666FF;">"mapOptionals"</span><span style="color: #F78811;">)</span> <span style="color: #000080;">=</span> forAll<span style="color: #F78811;">(</span><span style="color: #F78811;">(</span>f<span style="color: #000080;">:</span> <span style="color: #9999cc; font-weight: bold;">Int</span> <span style="color: #000080;">=&gt;</span> Optional<span style="color: #F78811;">[</span>String<span style="color: #F78811;">]</span>, o<span style="color: #000080;">:</span> List<span style="color: #F78811;">[</span><span style="color: #9999cc; font-weight: bold;">Int</span><span style="color: #F78811;">]</span><span style="color: #F78811;">)</span> <span style="color: #000080;">=&gt;</span>
  <span style="color: #F78811;">{</span>
    <span style="color: #0000ff; font-weight: bold;">val</span> i <span style="color: #000080;">=</span> o map f
    mapOptionals<span style="color: #F78811;">(</span>f, o<span style="color: #F78811;">)</span> <span style="color: #000080;">==</span> <span style="color: #F78811;">(</span><span style="color: #0000ff; font-weight: bold;">if</span><span style="color: #F78811;">(</span>i forall <span style="color: #F78811;">(</span><span style="color: #000080;">_</span>.<span style="color: #000000;">isDefined</span><span style="color: #F78811;">)</span><span style="color: #F78811;">)</span> some<span style="color: #F78811;">(</span>i map <span style="color: #F78811;">(</span><span style="color: #000080;">_</span>.<span style="color: #000000;">get</span><span style="color: #F78811;">)</span><span style="color: #F78811;">)</span> <span style="color: #0000ff; font-weight: bold;">else</span> none<span style="color: #F78811;">)</span>
  <span style="color: #F78811;">}</span><span style="color: #F78811;">)</span>
 
  property<span style="color: #F78811;">(</span><span style="color: #6666FF;">"sequenceOptionals"</span><span style="color: #F78811;">)</span> <span style="color: #000080;">=</span> forAll<span style="color: #F78811;">(</span><span style="color: #F78811;">(</span>o<span style="color: #000080;">:</span> List<span style="color: #F78811;">[</span>Optional<span style="color: #F78811;">[</span>String<span style="color: #F78811;">]</span><span style="color: #F78811;">]</span><span style="color: #F78811;">)</span> <span style="color: #000080;">=&gt;</span>
      sequenceOptionals<span style="color: #F78811;">(</span>o<span style="color: #F78811;">)</span> <span style="color: #000080;">==</span> <span style="color: #F78811;">(</span><span style="color: #0000ff; font-weight: bold;">if</span><span style="color: #F78811;">(</span>o exists <span style="color: #F78811;">(</span><span style="color: #000080;">_</span>.<span style="color: #000000;">isEmpty</span><span style="color: #F78811;">)</span><span style="color: #F78811;">)</span> none <span style="color: #0000ff; font-weight: bold;">else</span> some<span style="color: #F78811;">(</span>o map <span style="color: #F78811;">(</span><span style="color: #000080;">_</span>.<span style="color: #000000;">get</span><span style="color: #F78811;">)</span><span style="color: #F78811;">)</span><span style="color: #F78811;">)</span><span style="color: #F78811;">)</span>
 
  property<span style="color: #F78811;">(</span><span style="color: #6666FF;">"mapOptionalsAgain"</span><span style="color: #F78811;">)</span> <span style="color: #000080;">=</span> forAll<span style="color: #F78811;">(</span><span style="color: #F78811;">(</span>f<span style="color: #000080;">:</span> <span style="color: #9999cc; font-weight: bold;">Int</span> <span style="color: #000080;">=&gt;</span> Optional<span style="color: #F78811;">[</span>String<span style="color: #F78811;">]</span>, o<span style="color: #000080;">:</span> List<span style="color: #F78811;">[</span><span style="color: #9999cc; font-weight: bold;">Int</span><span style="color: #F78811;">]</span><span style="color: #F78811;">)</span> <span style="color: #000080;">=&gt;</span>
      mapOptionalsAgain<span style="color: #F78811;">(</span>f, o<span style="color: #F78811;">)</span> <span style="color: #000080;">==</span> mapOptionals<span style="color: #F78811;">(</span>f, o<span style="color: #F78811;">)</span><span style="color: #F78811;">)</span>
 
  property<span style="color: #F78811;">(</span><span style="color: #6666FF;">"sequenceOptionalsAgain"</span><span style="color: #F78811;">)</span> <span style="color: #000080;">=</span> forAll<span style="color: #F78811;">(</span><span style="color: #F78811;">(</span>o<span style="color: #000080;">:</span> List<span style="color: #F78811;">[</span>Optional<span style="color: #F78811;">[</span>String<span style="color: #F78811;">]</span><span style="color: #F78811;">]</span><span style="color: #F78811;">)</span> <span style="color: #000080;">=&gt;</span>
      sequenceOptionalsAgain<span style="color: #F78811;">(</span>o<span style="color: #F78811;">)</span> <span style="color: #000080;">==</span> sequenceOptionals<span style="color: #F78811;">(</span>o<span style="color: #F78811;">)</span><span style="color: #F78811;">)</span>
 
  property<span style="color: #F78811;">(</span><span style="color: #6666FF;">"joinOptionals"</span><span style="color: #F78811;">)</span> <span style="color: #000080;">=</span> forAll<span style="color: #F78811;">(</span><span style="color: #F78811;">(</span>o<span style="color: #000080;">:</span> Optional<span style="color: #F78811;">[</span>Optional<span style="color: #F78811;">[</span>String<span style="color: #F78811;">]</span><span style="color: #F78811;">]</span><span style="color: #F78811;">)</span> <span style="color: #000080;">=&gt;</span>
      joinOptionals<span style="color: #F78811;">(</span>o<span style="color: #F78811;">)</span> <span style="color: #000080;">==</span> <span style="color: #F78811;">(</span><span style="color: #0000ff; font-weight: bold;">if</span><span style="color: #F78811;">(</span>o.<span style="color: #000000;">isDefined</span> <span style="color: #000080;">&amp;&amp;</span> o.<span style="color: #000000;">get</span>.<span style="color: #000000;">isDefined</span><span style="color: #F78811;">)</span> o.<span style="color: #000000;">get</span> <span style="color: #0000ff; font-weight: bold;">else</span> none<span style="color: #F78811;">)</span><span style="color: #F78811;">)</span>
 
  property<span style="color: #F78811;">(</span><span style="color: #6666FF;">"filterOptionals"</span><span style="color: #F78811;">)</span> <span style="color: #000080;">=</span> forAll<span style="color: #F78811;">(</span><span style="color: #F78811;">(</span>f<span style="color: #000080;">:</span> <span style="color: #9999cc; font-weight: bold;">Int</span> <span style="color: #000080;">=&gt;</span> Optional<span style="color: #F78811;">[</span><span style="color: #9999cc; font-weight: bold;">Boolean</span><span style="color: #F78811;">]</span>, o<span style="color: #000080;">:</span> List<span style="color: #F78811;">[</span><span style="color: #9999cc; font-weight: bold;">Int</span><span style="color: #F78811;">]</span><span style="color: #F78811;">)</span> <span style="color: #000080;">=&gt;</span>
      filterOptionals<span style="color: #F78811;">(</span>f, o<span style="color: #F78811;">)</span> <span style="color: #000080;">==</span> <span style="color: #F78811;">(</span><span style="color: #0000ff; font-weight: bold;">if</span><span style="color: #F78811;">(</span>o exists <span style="color: #F78811;">(</span>f<span style="color: #F78811;">(</span><span style="color: #000080;">_</span><span style="color: #F78811;">)</span>.<span style="color: #000000;">isEmpty</span><span style="color: #F78811;">)</span><span style="color: #F78811;">)</span> none <span style="color: #0000ff; font-weight: bold;">else</span> some<span style="color: #F78811;">(</span>o filter <span style="color: #F78811;">(</span>f<span style="color: #F78811;">(</span><span style="color: #000080;">_</span><span style="color: #F78811;">)</span>.<span style="color: #000000;">get</span><span style="color: #F78811;">)</span><span style="color: #F78811;">)</span><span style="color: #F78811;">)</span><span style="color: #F78811;">)</span>
 
  property<span style="color: #F78811;">(</span><span style="color: #6666FF;">"fillOptionals"</span><span style="color: #F78811;">)</span> <span style="color: #000080;">=</span> forAll<span style="color: #F78811;">(</span><span style="color: #F78811;">(</span>n<span style="color: #000080;">:</span> <span style="color: #9999cc; font-weight: bold;">Int</span>, o<span style="color: #000080;">:</span> Optional<span style="color: #F78811;">[</span>String<span style="color: #F78811;">]</span><span style="color: #F78811;">)</span> <span style="color: #000080;">=&gt;</span>
      <span style="color: #F78811;">(</span>n <span style="color: #000080;">&lt;</span> <span style="color: #F78811;">1000</span><span style="color: #F78811;">)</span> <span style="color: #000080;">==&gt;</span> <span style="color: #008000; font-style: italic;">// prevent stack consumption</span>
      <span style="color: #F78811;">(</span>fillOptionals<span style="color: #F78811;">(</span>n, o<span style="color: #F78811;">)</span> <span style="color: #000080;">==</span> <span style="color: #F78811;">(</span><span style="color: #0000ff; font-weight: bold;">if</span><span style="color: #F78811;">(</span>n <span style="color: #000080;">&lt;=</span> <span style="color: #F78811;">0</span><span style="color: #F78811;">)</span> some<span style="color: #F78811;">(</span>Nil<span style="color: #F78811;">)</span> <span style="color: #0000ff; font-weight: bold;">else</span> <span style="color: #F78811;">(</span>o map <span style="color: #F78811;">(</span>List.<span style="color: #000000;">fill</span><span style="color: #F78811;">(</span>n<span style="color: #F78811;">)</span><span style="color: #F78811;">(</span><span style="color: #000080;">_</span><span style="color: #F78811;">)</span><span style="color: #F78811;">)</span><span style="color: #F78811;">)</span><span style="color: #F78811;">)</span><span style="color: #F78811;">)</span><span style="color: #F78811;">)</span>
 
  property<span style="color: #F78811;">(</span><span style="color: #6666FF;">"fillOptionalsAgain"</span><span style="color: #F78811;">)</span> <span style="color: #000080;">=</span> forAll<span style="color: #F78811;">(</span><span style="color: #F78811;">(</span>n<span style="color: #000080;">:</span> <span style="color: #9999cc; font-weight: bold;">Int</span>, o<span style="color: #000080;">:</span> Optional<span style="color: #F78811;">[</span>String<span style="color: #F78811;">]</span><span style="color: #F78811;">)</span> <span style="color: #000080;">=&gt;</span>
      <span style="color: #F78811;">(</span>n <span style="color: #000080;">&lt;</span> <span style="color: #F78811;">1000</span><span style="color: #F78811;">)</span> <span style="color: #000080;">==&gt;</span> <span style="color: #008000; font-style: italic;">// prevent stack consumption      </span>
      <span style="color: #F78811;">(</span>fillOptionalsAgain<span style="color: #F78811;">(</span>n, o<span style="color: #F78811;">)</span> <span style="color: #000080;">==</span> fillOptionals<span style="color: #F78811;">(</span>n, o<span style="color: #F78811;">)</span><span style="color: #F78811;">)</span><span style="color: #F78811;">)</span>
 
  property<span style="color: #F78811;">(</span><span style="color: #6666FF;">"mapOptionalsYetAgain"</span><span style="color: #F78811;">)</span> <span style="color: #000080;">=</span> forAll<span style="color: #F78811;">(</span><span style="color: #F78811;">(</span>f<span style="color: #000080;">:</span> <span style="color: #9999cc; font-weight: bold;">Int</span> <span style="color: #000080;">=&gt;</span> Optional<span style="color: #F78811;">[</span>String<span style="color: #F78811;">]</span>, o<span style="color: #000080;">:</span> List<span style="color: #F78811;">[</span><span style="color: #9999cc; font-weight: bold;">Int</span><span style="color: #F78811;">]</span><span style="color: #F78811;">)</span> <span style="color: #000080;">=&gt;</span>
      mapOptionalsYetAgain<span style="color: #F78811;">(</span>f, o<span style="color: #F78811;">)</span> <span style="color: #000080;">==</span> mapOptionals<span style="color: #F78811;">(</span>f, o<span style="color: #F78811;">)</span><span style="color: #F78811;">)</span>
 
  property<span style="color: #F78811;">(</span><span style="color: #6666FF;">"mapWhatever"</span><span style="color: #F78811;">)</span> <span style="color: #000080;">=</span> forAll<span style="color: #F78811;">(</span><span style="color: #F78811;">(</span>f<span style="color: #000080;">:</span> <span style="color: #9999cc; font-weight: bold;">Int</span> <span style="color: #000080;">=&gt;</span> Optional<span style="color: #F78811;">[</span>String<span style="color: #F78811;">]</span>, o<span style="color: #000080;">:</span> List<span style="color: #F78811;">[</span><span style="color: #9999cc; font-weight: bold;">Int</span><span style="color: #F78811;">]</span><span style="color: #F78811;">)</span> <span style="color: #000080;">=&gt;</span>
      mapWhatever<span style="color: #F78811;">(</span>f, o<span style="color: #F78811;">)</span> <span style="color: #000080;">==</span> mapOptionals<span style="color: #F78811;">(</span>f, o<span style="color: #F78811;">)</span><span style="color: #F78811;">)</span>
 
  <span style="color: #00ff00; font-style: italic;">/*
  $ scala -classpath .:scalacheck_2.8.0-1.7.jar TestOptional
  + Optional.map: OK, passed 100 tests.                                         
  + Optional.get: OK, passed 100 tests.                                         
  + Optional.flatMap: OK, passed 100 tests.                                     
  + Optional.mapAgain: OK, passed 100 tests.                                    
  + Optional.getOrElse: OK, passed 100 tests.                                   
  + Optional.filter: OK, passed 100 tests.                                      
  + Optional.exists: OK, passed 100 tests.                                      
  + Optional.forall: OK, passed 100 tests.                                      
  + Optional.foreach: OK, passed 100 tests.                                     
  + Optional.isDefined: OK, passed 100 tests.                                   
  + Optional.isEmpty: OK, passed 100 tests.                                     
  + Optional.orElse: OK, passed 100 tests.                                      
  + Optional.toLeft: OK, passed 100 tests.                                      
  + Optional.toRight: OK, passed 100 tests.                                     
  + Optional.toList: OK, passed 100 tests.                                      
  + Optional.iterator: OK, passed 100 tests.                                    
  + Optional.applic: OK, passed 100 tests.                                      
  + Optional.mapOptionals: OK, passed 100 tests.                                
  + Optional.sequenceOptionals: OK, passed 100 tests.                           
  + Optional.mapOptionalsAgain: OK, passed 100 tests.                           
  + Optional.sequenceOptionalsAgain: OK, passed 100 tests.                      
  + Optional.joinOptionals: OK, passed 100 tests.                               
  + Optional.filterOptionals: OK, passed 100 tests.                             
  + Optional.fillOptionals: OK, passed 100 tests.                          
  + Optional.fillOptionalsAgain: OK, passed 100 tests.                     
  + Optional.mapOptionalsYetAgain: OK, passed 100 tests.                        
  + Optional.mapWhatever: OK, passed 100 tests.          
  */</span>  
<span style="color: #F78811;">}</span></pre></div></div></div>
    </content>
    <updated>2010-09-01T05:45:27Z</updated>
    <category term="Programming"/>
    <author>
      <name>Tony Morris</name>
    </author>
    <source>
      <id>http://blog.tmorris.net</id>
      <link href="http://blog.tmorris.net/category/programming/feed/" rel="self" type="application/atom+xml"/>
      <link href="http://blog.tmorris.net" rel="alternate" type="text/html"/>
      <subtitle>The weblog of Tony Morris</subtitle>
      <title>λ Tony’s blog λ » Programming</title>
      <updated>2010-09-01T23:54:25Z</updated>
    </source>
  </entry>

  <entry>
    <id>tag:blogger.com,1999:blog-7317245822288637185.post-3958937033472697238</id>
    <link href="http://grahamhackingscala.blogspot.com/feeds/3958937033472697238/comments/default" rel="replies" type="application/atom+xml"/>
    <link href="http://grahamhackingscala.blogspot.com/2010/08/impossible-possible-intellij-idea-love.html#comment-form" rel="replies" type="text/html"/>
    <link href="http://www.blogger.com/feeds/7317245822288637185/posts/default/3958937033472697238?v=2" rel="edit" type="application/atom+xml"/>
    <link href="http://www.blogger.com/feeds/7317245822288637185/posts/default/3958937033472697238?v=2" rel="self" type="application/atom+xml"/>
    <link href="http://feedproxy.google.com/~r/blogspot/vnby/~3/At9AK2UWf78/impossible-possible-intellij-idea-love.html" rel="alternate" type="text/html"/>
    <title>Things I Love About IntelliJ IDEA: The Impossible is Possible</title>
    <content type="xhtml"><div xmlns="http://www.w3.org/1999/xhtml">The features I've written about so far are the ones that I use really often and that I find make the biggest difference for me when I use IntelliJ IDEA. Some of them are a bit mundane, but when I have to code without them I often get the feeling of being bogged down in typing boilerplate.<br/><br/>But there is another side to IntelliJ - an exciting side! IDEA has a whole host of features which, to me, are bordering on mind-blowing. There are quite a few features in IDEA that are so impressive that I don't just think, "That's a clever idea. I'm glad they put that in." What I really think is, "How the hell did they even IMAGINE that that was POSSIBLE?!" Seriously, the Jetbrains guys have implemented tools that I would have laughed at if they were proposed to me, just from the sheer audacity of the ideas and the complexity that I imagine would be involved in implementing them.<br/><br/>One domain where they have been impressing me lately is in their Hibernate integration. If you tell IDEA about a datasource that your Hibernate entities should be able to map to, it can do some cool things like tell you that no table exists with the same name as your entity, or that the column name in your @Column annotation doesn't match any column in the database table. There's also <a href="http://www.jetbrains.com/idea/features/jpa_hibernate.html#link6" target="_blank">the HQL console</a>, where you can run HQL queries against your database, complete with code-completion from your domain model. Both of these are "Cool, that's useful" features, but I imagine your mouth is not yet agape.<br/><br/>Then they go to the next level: the same code completion that's available in the HQL editor is also available write in the middle of your code <a href="http://blogs.jetbrains.com/idea/2009/03/user-defined-language-injection/" target="_blank">using language injection</a>. That's right, those Strings in your Repository classes are no longer just Strings - that first double quote now denotes the point at which Java stops and HQL starts, and IDEA will give you all the help you need to write a query that is correct both syntactically and in respect of your domain model, with name completion, underlining of errors and meaningful error messages. (To enable HQL editing in a class just hit Alt-Enter, select 'Inject Language', then 'HQL')<br/><br/>But after the Jetbrains guys implemented that awesome integration, they got bored, so they had to think of something even more amazing to integrate. Now I see that in the upcoming IntelliJ IDEA X, they have <a href="http://blogs.jetbrains.com/idea/2010/08/hibernate-criteria-api-supported-in-intellij-idea-x/" target="_blank">added similar integration to queries created using Hibernate's Criteria API</a>. The ingenuity involved in this feature astounds me - IDEA is observing the annotations on Hibernate entities, parsing Java code and recognising a Criteria query, then building enough understanding of that query and linking it in with the knowledge from the entity classes to be able to make suggestions about the possible and legal properties and relationships that could be queried. It's another example of <a href="http://grahamhackingscala.blogspot.com/2010/08/intentional-programming-intellij-idea.html" target="_blank">IDEA being so intelligent that it probably knows more about my code than I do</a>, and the guys have probably re-written half of Hibernate in order to give it to us.<br/><br/>As I said, this is just one domain (no pun intended) that has been impressing me lately. IntelliJ IDEA is full of little nuggets likes this where the Jetbrains developers have dreamed up and then delivered features that are useful so far beyond any little improvements or tweaks that I could have requested as a day-to-day user. This isn't the product of a team of developers tirelessly implementing feature requests from users - it's the constantly evolving creation of a group of highly visionary people who intimately understand the day to day tasks of a coder but are also able to rise above the detail and imagine a better future where the tools don't just help out with the boilerplate but also start to take on some of the heavy lifting.<div class="blogger-post-footer"><img alt="" height="1" src="https://blogger.googleusercontent.com/tracker/7317245822288637185-3958937033472697238?l=grahamhackingscala.blogspot.com" width="1"/></div>
<p><a href="http://feedads.g.doubleclick.net/~a/rG33UirqS9Npq5rtikOYEkCsqC8/0/da"><img border="0" ismap="true" src="http://feedads.g.doubleclick.net/~a/rG33UirqS9Npq5rtikOYEkCsqC8/0/di"/></a><br/>
<a href="http://feedads.g.doubleclick.net/~a/rG33UirqS9Npq5rtikOYEkCsqC8/1/da"><img border="0" ismap="true" src="http://feedads.g.doubleclick.net/~a/rG33UirqS9Npq5rtikOYEkCsqC8/1/di"/></a></p><img height="1" src="http://feeds.feedburner.com/~r/blogspot/vnby/~4/At9AK2UWf78" width="1"/></div>
    </content>
    <updated>2010-09-01T01:32:44Z</updated>
    <published>2010-09-01T01:01:00Z</published>
    <category scheme="http://www.blogger.com/atom/ns#" term="error highlighting"/>
    <category scheme="http://www.blogger.com/atom/ns#" term="java"/>
    <category scheme="http://www.blogger.com/atom/ns#" term="intellij"/>
    <category scheme="http://www.blogger.com/atom/ns#" term="jpa"/>
    <category scheme="http://www.blogger.com/atom/ns#" term="eclipse"/>
    <category scheme="http://www.blogger.com/atom/ns#" term="intelligent"/>
    <category scheme="http://www.blogger.com/atom/ns#" term="compare"/>
    <category scheme="http://www.blogger.com/atom/ns#" term="possible"/>
    <category scheme="http://www.blogger.com/atom/ns#" term="impossible"/>
    <category scheme="http://www.blogger.com/atom/ns#" term="syntax"/>
    <category scheme="http://www.blogger.com/atom/ns#" term="comparison"/>
    <category scheme="http://www.blogger.com/atom/ns#" term="hibernate"/>
    <category scheme="http://www.blogger.com/atom/ns#" term="hql"/>
    <category scheme="http://www.blogger.com/atom/ns#" term="domain model"/>
    <category scheme="http://www.blogger.com/atom/ns#" term="integration"/>
    <category scheme="http://www.blogger.com/atom/ns#" term="jetbrains"/>
    <category scheme="http://www.blogger.com/atom/ns#" term="idea"/>
    <category scheme="http://www.blogger.com/atom/ns#" term="repository"/>
    <category scheme="http://www.blogger.com/atom/ns#" term="annotations"/><feedburner:origLink xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0">http://grahamhackingscala.blogspot.com/2010/08/impossible-possible-intellij-idea-love.html</feedburner:origLink>
    <author>
      <name>Grazer</name>
      <email>noreply@blogger.com</email>
      <uri>http://www.blogger.com/profile/00435359638152521056</uri>
    </author>
    <source>
      <id>tag:blogger.com,1999:blog-7317245822288637185</id>
      <author>
        <name>Grazer</name>
        <email>noreply@blogger.com</email>
        <uri>http://www.blogger.com/profile/00435359638152521056</uri>
      </author>
      <link href="http://grahamhackingscala.blogspot.com/feeds/posts/default" rel="http://schemas.google.com/g/2005#feed" type="application/atom+xml"/>
      <link href="http://grahamhackingscala.blogspot.com/" rel="alternate" type="text/html"/>
      <link href="http://feeds.feedburner.com/blogspot/vnby" rel="self" type="application/atom+xml"/>
      <link href="http://pubsubhubbub.appspot.com/" rel="hub" type="text/html"/>
      <subtitle>The point of "Graham Hacking Scala" is to share with you my knowledge of and experience with the Scala programming language. The blog will contain everything from introductions to basic features through to in-depth analysis of complex techniques and problems. When I make mistakes, you will learn from my mistakes. When I discover cool features, you will learn about them, too.</subtitle>
      <title>Graham Hacking Scala</title>
      <updated>2010-09-04T16:58:00Z</updated>
    </source>
  </entry>

  <entry xml:lang="en">
    <id>http://blog.darevay.com/?p=243</id>
    <link href="http://blog.darevay.com/2010/08/scripting-jsoar/" rel="alternate" type="text/html"/>
    <title>Scripting JSoar</title>
    <summary>In simpler times (say 2001) Soar was just Tcl. That is to say, Soar was a module, dynamically loaded into a Tcl interpreter at run-time. When loaded, Soar added a bunch of useful commands to the interpreter. Like run, matches, preferences, and probably most importantly, the sp command. When you “sourced” a Soar file, the [...]</summary>
    <content type="xhtml"><div xmlns="http://www.w3.org/1999/xhtml"><p>In simpler times (say 2001) Soar was just <a href="http://en.wikipedia.org/wiki/Tcl">Tcl</a>. That is to say, Soar was a module, dynamically loaded into a Tcl interpreter at run-time. When loaded, Soar added a bunch of useful commands to the interpreter. Like <strong>run</strong>, <strong>matches</strong>, <strong>preferences</strong>, and probably most importantly, the <strong>sp</strong> command. When you “sourced” a Soar file, the Tcl interpreter just executed commands, loading rules, setting watch levels, etc.</p>
<p>The main drawback to this whole situation was that Tcl didn’t always lend itself to friendly embedding in other programs. It had funny rules about threads and, if Tk was involved, demanded to have its message queue pumped. And, of course, very few people get to know Tcl enough to like it :)</p>
<p>On the other hand, you could create macros for repetitive Soar structures, define new RHS functions, manipulate I/O. In short, you had the power of a full programming language mixed in with your Soar code.</p>
<p>With Soar 8.6 Soar’s tight integration with Tcl was broken, replaced by SML and a stricter command interpreter. It still looked like Tcl commands, but there were no Tcl control structures, variables, etc. Way it goes. When I initially started work on JSoar, I needed to quickly bootstrap a command interpreter so I could load existing code into the kernel. I turned to Tcl, in the form of <a href="http://wiki.tcl.tk/1637">Jacl</a>, a Java implementation of Tcl. It saved a lot of time and, since Soar’s syntax was still basically Tcl, no one would really notice.</p>
<p>Of course, as I mentioned, no one wants Tcl, so over the last couple weeks, I’ve added a new scripting layer to JSoar. This time, I’m taking advantage of the <a href="https://scripting.dev.java.net/">Java Scripting API, JSR-223</a>. This allows any scripting language with a JSR-223 implementation to be pretty seamlessly accessed from Java (and vice versa). With this new capability, it’s now possible to automate Soar agents, implement simple agent environments, and extend SoarUnit testing to include I/O, all from within a Soar source file. All with a variety of languages including Ruby, JavaScript, Python, Clojure, Groovy, etc.</p>
<p>A scripting engine (a language implementation) is invoked with the <strong>script</strong> command:</p>
<pre>script javascript {
   soar.onInput(function(e) {
      soar.wmes.add("my-input", "hello");
   });
   soar.onOutputCommand("say", function(e) {
      soar.print("The agent says: " + e.greeting);
   });
}
</pre>
<p>This little bit of code sets up an input phase callback and creates a WME on the agen’ts input-link. It also handles an output command called “say”. The equivalent Java code would be … more ceremonious. Not to mention setting up a new project, compiling, etc, etc is a major hassle.</p>
<p>As an example, I’ve implemented a simple <a href="http://www.binding-time.co.uk/water_jugs.html">waterjugs </a>environment in <a href="http://code.google.com/p/jsoar/source/browse/jsoar-demos/demos/scripting/waterjugs-js.soar">JavaScript</a>, <a href="http://code.google.com/p/jsoar/source/browse/jsoar-demos/demos/scripting/waterjugs-rb.soar">Ruby</a>, and <a href="http://code.google.com/p/jsoar/source/browse/jsoar-demos/demos/scripting/waterjugs-py.soar">Python</a>. Here are some things you can do:</p>
<ul>
<li>Generate input</li>
<li>Handle output commands</li>
<li>Auto-convert hashes (JavaScript objects, Python dicts, or Ruby hashes) to input structures</li>
<li>Install new RHS functions</li>
<li>Add new commands</li>
<li>and on and on</li>
</ul>
<p>Also, with maybe a little more work, I might have a pretty good story for dealing with I/O in <a href="http://blog.darevay.com/2010/08/introducing-soarunit/">SoarUnit tests</a>. Stay tuned.</p>
<p>More detailed info on JSoar scripting support can be found on the <a href="http://code.google.com/p/jsoar/wiki/JSoarScripting">JSoar wiki</a>.</p></div>
    </content>
    <updated>2010-08-31T03:15:22Z</updated>
    <category term="Uncategorized"/>
    <category term="soar"/>
    <category term="javascript"/>
    <category term="jsoar"/>
    <category term="python"/>
    <category term="ruby"/>
    <category term="scripting"/>
    <author>
      <name>dave</name>
    </author>
    <source>
      <id>http://blog.darevay.com</id>
      <link href="http://blog.darevay.com" rel="alternate" type="text/html"/>
      <link href="http://feeds.feedburner.com/darevay" rel="self" type="application/atom+xml"/>
      <link href="http://pubsubhubbub.appspot.com/" rel="hub" type="text/html"/>
      <subtitle>You know, software and some other stuff like maybe guitar or something</subtitle>
      <title>Along Came Betty</title>
      <updated>2010-08-31T03:20:13Z</updated>
    </source>
  </entry>

  <entry>
    <id>tag:blogger.com,1999:blog-178174920347765771.post-2589355882870196097</id>
    <link href="http://james-iry.blogspot.com/2010/08/why-scalas-and-haskells-types-will-save.html" rel="alternate" type="text/html"/>
    <title>Why Scala's "Option" and Haskell's "Maybe" types will save you from null</title>
    <summary>Cedric Beust makes a bunch of claims in his post on Why Scala's "Option" and Haskell's "Maybe" types won't save you from null, commenters say he doesn't get it and he says nobody has argued with his main points.  So I thought I'd do a careful investigation to see what, if anything, is being missed.First, right off the top here: Scala has true blue Java-like null; any reference may be null.  Its</summary>
    <updated>2010-08-27T20:55:00Z</updated>
    <category scheme="http://www.blogger.com/atom/ns#" term="haskell"/>
    <category scheme="http://www.blogger.com/atom/ns#" term="scala"/>
    <author>
      <name>James Iry</name>
      <email>noreply@blogger.com</email>
    </author>
    <source>
      <id>tag:blogger.com,1999:blog-178174920347765771</id>
      <author>
        <name>James Iry</name>
        <email>noreply@blogger.com</email>
      </author>
      <link href="http://james-iry.blogspot.com/" rel="alternate" type="text/html"/>
      <link href="http://james-iry.blogspot.com/feeds/posts/default?alt=rss" rel="self" type="application/atom+xml"/>
      <subtitle>An exploration of software development.</subtitle>
      <title>One Div Zero</title>
      <updated>2010-09-03T03:01:02Z</updated>
    </source>
  </entry>

  <entry>
    <id>http://code.technically.us/post/1020789668</id>
    <link href="http://code.technically.us/post/1020789668" rel="alternate" type="text/html"/>
    <title>"I’ll make you a deal: once Mac Rumors and Macworld update their respective articles that make..."</title>
    <summary type="xhtml"><div xmlns="http://www.w3.org/1999/xhtml">“I’ll make you a deal: once Mac Rumors and Macworld update their respective articles that make exactly the same points I did, I’ll update mine. Until then, I won’t defer to the wisdom of the internet’s armchair licensing experts.”<br/><br/> - <em><a href="http://www.tuaw.com/2010/08/26/royalty-free-h-264-is-a-big-win-for-html5-big-loss-for-flash/3#comments">Adventures in Oblivious Self-Contradiction</a></em></div>
    </summary>
    <updated>2010-08-27T18:19:00Z</updated>
    <category term="Armchairs"/>
    <category term="Experts"/>
    <category term="Dumb Property"/>
    <category term="New Media"/>
    <category term="Video"/>
    <category term="Patents"/>
    <source>
      <id>http://code.technically.us/</id>
      <author>
        <name>Coderspiel</name>
      </author>
      <link href="http://tumblr.superfeedr.com/" rel="hub" type="text/html"/>
      <link href="http://code.technically.us/" rel="alternate" type="text/html"/>
      <link href="http://code.technically.us/rss" rel="self" type="application/rss+xml"/>
      <title>Coderspiel</title>
      <updated>2010-09-09T03:00:39Z</updated>
    </source>
  </entry>

  <entry>
    <id>tag:blogger.com,1999:blog-22587889.post-771609389628045845</id>
    <link href="http://debasishg.blogspot.com/feeds/771609389628045845/comments/default" rel="replies" type="application/atom+xml"/>
    <link href="https://www.blogger.com/comment.g?blogID=22587889&amp;postID=771609389628045845" rel="replies" type="text/html"/>
    <link href="http://www.blogger.com/feeds/22587889/posts/default/771609389628045845" rel="edit" type="application/atom+xml"/>
    <link href="http://debasishg.blogspot.com/feeds/posts/default/771609389628045845" rel="self" type="application/atom+xml"/>
    <link href="http://debasishg.blogspot.com/2010/08/random-thoughts-on-clojure-protocols.html" rel="alternate" type="text/html"/>
    <title>Random thoughts on Clojure Protocols</title>
    <content type="xhtml"><div xmlns="http://www.w3.org/1999/xhtml">Great languages are those that offer orthogonality in design. Stated simply it means that the language core offers a minimal set of non-overlapping ways to compose abstractions. In an earlier article <a href="http://debasishg.blogspot.com/2010/01/case-for-orthogonality-in-design.html">A Case for Orthogonality in Design</a> I discussed some features from languages like Haskell, C++ and Scala that help you compose higher order abstractions from smaller ones using techniques offered by those languages.<br/><br/>In this post I discuss the new feature in Clojure that just made its way in the recently released 1.2. I am not going into what Protocols are - there are quite a <a href="http://kirindave.tumblr.com/post/658770511/monkey-patching-gorilla-engineering-protocols-in">few</a> <a href="http://freegeek.in/blog/2010/05/clojure-protocols-datatypes-a-sneak-peek/">nice</a> articles that introduce <a href="http://www.assembla.com/wiki/show/clojure/Protocols">Clojure Protocols</a> and the associated <code>defrecord</code> and <code>deftype</code> forms. This post will be some random rants about how protocols encourage non intrusive extension of abstractions without muddling inheritance into polymorphism. I also discuss some of my realizations about what protocols aren't, which I felt was equally important along with understanding what they are.<br/><br/>Let's start with the familiar <code>Show</code> type class of Haskell ..<br/><br/><code><span class="java_operator">&gt;</span><span class="java_plain"> </span><span class="java_operator">:</span><span class="java_plain">t show</span></code><br/><code><span class="java_plain">show </span><span class="java_operator">::</span><span class="java_plain"> </span><span class="java_separator">(</span><span class="java_type">Show</span><span class="java_plain"> a</span><span class="java_separator">)</span><span class="java_plain"> </span><span class="java_operator">=&gt;</span><span class="java_plain"> a </span><span class="java_operator">-&gt;</span><span class="java_plain"> </span><span class="java_type">String</span><span class="java_plain"/><br/><span class="java_plain"/></code><br/>Takes a type and renders a string for it. You get <code>show</code> for your class if you have implemented it as an instance of the <code>Show</code> type class. The <code>Show</code> type class extends your abstraction transparently through an additional behavior set. We can do the same thing using protocols in Clojure ..<br/><br/><code><span class="java_separator">(</span><span class="java_keyword">defprotocol</span><span class="java_plain"> SHOW </span></code><br/><code><span class="java_plain">  </span><span class="java_separator">(</span><span class="java_plain">show </span><span class="java_separator">[</span><span class="java_plain">val</span><span class="java_separator">]))</span><span class="java_plain"/><br/><span class="java_plain"/></code><br/>The protocol definition just <i>declares</i> the contract without any <i>concrete implementation</i> in it. Under the covers it generates a Java interface which you can use in your Java code as well. <i>But a protocol is not an interface</i>.<br/><br/><b>Adding behaviors non-invasively ..</b><br/><br/>I can extend an existing type with the behaviors of this protocol. And for this I need not have the source code for the type. This is one of the benefits that <a href="http://www.haskell.org/haskellwiki/Ad-hoc_polymorphism">ad hoc polymorphism</a> of type classes offers - type classes (and Clojure protocols) are <i>open</i>. Note how this is in contrast to the compile time coupling of Java interface and inheritance.<br/><br/>Extending <code>java.lang.Integer</code> with <code>SHOW</code> ..<br/><br/><code><span class="java_separator">(</span><span class="java_keyword">extend-type</span><span class="java_plain"> </span><span class="java_type">Integer</span><span class="java_plain"/></code><br/><code><span class="java_plain">  SHOW</span><br/><span class="java_plain">  </span><span class="java_separator">(</span><span class="java_plain">show </span><span class="java_separator">[</span><span class="java_plain">i</span><span class="java_separator">]</span><span class="java_plain"> </span><span class="java_separator">(.</span><span class="java_plain">toString i</span><span class="java_separator">)))</span><span class="java_plain"/><br/><span class="java_plain"/></code><br/>We can extend an interface also. And get access to the added behavior from *any* of its implementations .. Here's extending <code>clojure.lang.IPersistentVector</code> ..<br/><br/><code><span class="java_separator">(</span><span class="java_keyword">extend-type</span><span class="java_plain"> clojure</span><span class="java_separator">.</span><span class="java_plain">lang</span><span class="java_separator">.</span><span class="java_type">IPersistentVector</span><span class="java_plain"/></code><br/><code><span class="java_plain">  SHOW</span><br/><span class="java_plain">  </span><span class="java_separator">(</span><span class="java_plain">show </span><span class="java_separator">[</span><span class="java_plain">v</span><span class="java_separator">]</span><span class="java_plain"> </span><span class="java_separator">(.</span><span class="java_plain">toString v</span><span class="java_separator">)))</span><span class="java_plain"/><br/><span class="java_plain"/><br/><span class="java_separator">(</span><span class="java_plain">show </span><span class="java_separator">[</span><span class="java_literal">12</span><span class="java_plain"> </span><span class="java_literal">1</span><span class="java_plain"> </span><span class="java_literal">4</span><span class="java_plain"> </span><span class="java_literal">15</span><span class="java_plain"> </span><span class="java_literal">2</span><span class="java_plain"> </span><span class="java_literal">4</span><span class="java_plain"> </span><span class="java_literal">67</span><span class="java_separator">])</span><span class="java_plain"/><br/><span class="java_operator">&gt;</span><span class="java_plain"> </span><span class="java_literal">"[12 1 4 15 2 4 67]"</span><span class="java_plain"/><br/><span class="java_plain"/></code><br/>And of course I can extend my own abstractions with the new behavior ..<br/><br/><code><span class="java_separator">(</span><span class="java_keyword">defrecord</span><span class="java_plain"> </span><span class="java_type">Name</span><span class="java_plain"> </span><span class="java_separator">[</span><span class="java_plain">last first</span><span class="java_separator">])</span><span class="java_plain"/></code><br/><code><span class="java_plain"/><br/><span class="java_separator">(</span><span class="java_keyword">defn</span><span class="java_plain"> name</span><span class="java_operator">-</span><span class="java_plain">desc </span><span class="java_separator">[</span><span class="java_plain">name</span><span class="java_separator">]</span><span class="java_plain"/><br/><span class="java_plain">  </span><span class="java_separator">(</span><span class="java_plain">str </span><span class="java_separator">(</span><span class="java_operator">:</span><span class="java_plain">last name</span><span class="java_separator">)</span><span class="java_plain"> </span><span class="java_literal">" "</span><span class="java_plain"> </span><span class="java_separator">(</span><span class="java_operator">:</span><span class="java_plain">first name</span><span class="java_separator">)))</span><span class="java_plain"/><br/><span class="java_plain"/><br/><span class="java_separator">(</span><span class="java_plain">name</span><span class="java_operator">-</span><span class="java_plain">desc </span><span class="java_separator">(</span><span class="java_type">Name</span><span class="java_separator">.</span><span class="java_plain"> </span><span class="java_literal">"ghosh"</span><span class="java_plain"> </span><span class="java_literal">"debasish"</span><span class="java_separator">))</span><span class="java_plain"> </span><span class="java_separator">;;</span><span class="java_plain"> </span><span class="java_literal">"ghosh debasish"</span><span class="java_plain"/><br/><span class="java_plain"/><br/><span class="java_separator">(</span><span class="java_keyword">extend-type</span><span class="java_plain"> </span><span class="java_type">Name</span><span class="java_plain"/><br/><span class="java_plain">  SHOW</span><br/><span class="java_plain">  </span><span class="java_separator">(</span><span class="java_plain">show </span><span class="java_separator">[</span><span class="java_plain">n</span><span class="java_separator">]</span><span class="java_plain"/><br/><span class="java_plain">    </span><span class="java_separator">(</span><span class="java_plain">name</span><span class="java_operator">-</span><span class="java_plain">desc n</span><span class="java_separator">)))</span><span class="java_plain"/><br/><span class="java_plain"/><br/><span class="java_separator">(</span><span class="java_plain">show </span><span class="java_separator">(</span><span class="java_type">Name</span><span class="java_separator">.</span><span class="java_plain"> </span><span class="java_literal">"ghosh"</span><span class="java_plain"> </span><span class="java_literal">"debasish"</span><span class="java_separator">))</span><span class="java_plain"> </span><span class="java_separator">;;</span><span class="java_plain"> </span><span class="java_literal">"ghosh debasish"</span><span class="java_plain"/><br/><span class="java_plain"/></code><br/><b>No Inheritance</b><br/><br/>Protocols help you wire abstractions that are in no way related to each other. And it does this non-invasively. An object conforms to a protocol only if it implements the contract. As I mentioned before, there's no notion of hierarchy or inheritance related to this form of polymorphism.<br/><br/><b>No object bloat, no monkey patching</b><br/><br/>And there's no object bloat going on here. You can invoke <code>show</code> on any abstraction for which you implement the protocol, but <code>show</code> is never added as a method on that object. As an example try the following after implementing <code>SHOW</code> for <code>Integer</code> ..<br/><br/><code><span class="java_separator">(</span><span class="java_plain">filter #</span><span class="java_separator">(</span><span class="java_operator">=</span><span class="java_plain"> </span><span class="java_literal">"show"</span><span class="java_plain"> </span><span class="java_separator">(.</span><span class="java_plain">getName </span><span class="java_operator">%</span><span class="java_separator">))</span><span class="java_plain"> </span><span class="java_separator">(.</span><span class="java_plain">getMethods </span><span class="java_type">Integer</span><span class="java_separator">))</span><span class="java_plain"/></code><br/><code><span class="java_plain"/></code><br/>will return an empty list. Hence there is no scope of *accidentally* overriding some one else's monkey patch on some shared class.<br/><br/><b>Not really a type class</b><br/><br/>Clojure protocols dispatch on the first argument of the methods. This limits its ability from getting the full power that Haskell / Scala type classes offer. Consider the counterpart of <code>Show</code> in Haskell, which is the Read type class ..<br/><br/><code><span class="java_operator">&gt;</span><span class="java_plain"> </span><span class="java_operator">:</span><span class="java_plain">t read  </span></code><br/><code><span class="java_plain">read </span><span class="java_operator">::</span><span class="java_plain"> </span><span class="java_separator">(</span><span class="java_type">Read</span><span class="java_plain"> a</span><span class="java_separator">)</span><span class="java_plain"> </span><span class="java_operator">=&gt;</span><span class="java_plain"> </span><span class="java_type">String</span><span class="java_plain"> </span><span class="java_operator">-&gt;</span><span class="java_plain"> a</span><br/><span class="java_plain"/></code><br/>If your abstraction implements <code>Read</code>, then the exact instance of the method invoked will depend on the return type. e.g.<br/><br/><code><span class="java_operator">&gt;</span><span class="java_plain"> </span><span class="java_separator">[</span><span class="java_literal">1</span><span class="java_separator">,</span><span class="java_literal">2</span><span class="java_separator">,</span><span class="java_literal">3</span><span class="java_separator">]</span><span class="java_plain"> </span><span class="java_operator">++</span><span class="java_plain"> read </span><span class="java_literal">"[4,5,6]"</span><span class="java_plain"/></code><br/><code><span class="java_operator">=&gt;</span><span class="java_plain"> </span><span class="java_separator">[</span><span class="java_literal">1</span><span class="java_separator">,</span><span class="java_literal">2</span><span class="java_separator">,</span><span class="java_literal">3</span><span class="java_separator">,</span><span class="java_literal">4</span><span class="java_separator">,</span><span class="java_literal">5</span><span class="java_separator">,</span><span class="java_literal">6</span><span class="java_separator">]</span><span class="java_plain"/><br/><span class="java_plain"/></code><br/>The specific instance of <code>read</code> that returns a list of integers is automatically invoked here. Haskell maintains the dispatch match as part of its global dictionary.<br/><br/>We cannot do this in Clojure protocols, since it's unable to dispatch based on the return type. Protocols dispatch only on the first argument of the function.<br/><br/><br/><span class="Apple-style-span" style="font-family: Arial; font-size: small;"><span class="Apple-style-span" style="font-size: 13px;"/></span><div class="blogger-post-footer"><img alt="" height="1" src="https://blogger.googleusercontent.com/tracker/22587889-771609389628045845?l=debasishg.blogspot.com" width="1"/></div></div>
    </content>
    <updated>2010-08-27T16:45:39Z</updated>
    <published>2010-08-27T16:45:00Z</published>
    <category scheme="http://www.blogger.com/atom/ns#" term="clojure"/>
    <author>
      <name>Debasish</name>
      <email>ghosh.debasish@gmail.com</email>
      <uri>http://www.blogger.com/profile/01613713587074301135</uri>
    </author>
    <source>
      <id>tag:blogger.com,1999:blog-22587889</id>
      <author>
        <name>Debasish</name>
        <email>ghosh.debasish@gmail.com</email>
        <uri>http://www.blogger.com/profile/01613713587074301135</uri>
      </author>
      <link href="http://debasishg.blogspot.com/feeds/posts/full" rel="http://schemas.google.com/g/2005#feed" type="application/atom+xml"/>
      <link href="http://debasishg.blogspot.com/" rel="alternate" type="text/html"/>
      <link href="http://debasishg.blogspot.com/feeds/posts/full?start-index=4&amp;max-results=3" rel="next" type="application/atom+xml"/>
      <link href="http://feeds.feedburner.com/RuminationsOfAProgrammer" rel="self" type="application/atom+xml"/>
      <link href="http://pubsubhubbub.appspot.com/" rel="hub" type="text/html"/>
      <subtitle>A programmer's blog - will deal with everything that relates to a programmer. Occasionally, it will contain some humour, some politics and some sport news.</subtitle>
      <title>Ruminations of a Programmer</title>
      <updated>2010-09-03T15:56:25Z</updated>
    </source>
  </entry>

  <entry xml:lang="en">
    <id>http://www.scala-ide.org/?p=239</id>
    <link href="http://www.scala-ide.org/2010/08/google-summer-of-code-2010/" rel="alternate" type="text/html"/>
    <link href="http://www.scala-ide.org/2010/08/google-summer-of-code-2010/#comments" rel="replies" type="text/html"/>
    <link href="http://www.scala-ide.org/2010/08/google-summer-of-code-2010/feed/atom/" rel="replies" type="application/atom+xml"/>
    <title xml:lang="en">Google Summer of Code 2010 @ Scala IDE</title>
    <summary xml:lang="en">UPDATE: an update site including Jin’s GSoC work is now available.
I was lucky enough to be the mentor on a Scala IDE for Eclipse project which was selected for this year’s Google Summer of Code. Jin Mingjian was the student for this project, and it’s been wonderful to work with him over the last few [...]</summary>
    <content type="xhtml" xml:lang="en"><div xmlns="http://www.w3.org/1999/xhtml"><p><b>UPDATE: an update site including Jin’s GSoC work is now <a href="http://download.scala-ide.org/">available</a>.</b></p>
<p>I was lucky enough to be the mentor on a Scala IDE for Eclipse project which was selected for this year’s Google Summer of Code. <a href="http://www.linkedin.com/in/jinmingjian">Jin Mingjian</a> was the student for this project, and it’s been wonderful to work with him over the last few months.</p>
<p>Jin completed his Doctoral degree at the Institute of Electrical Engineering in the Chinese Academy of Sciences this summer … having to deal with his PhD defence at the same time as the GSoC project was quite a tall order!</p>
<p>He had this to say about himself and about his project …</p>
<hr/>
<p/>
<p>I have been involved with the Eclipse community for a long time. When I discovered Scala this year, I realized that it was the language that I need. The openness of Scala struck me, as much as the technical merits of the language itself. The Scala IDE community combines two great open source communities and this summer’s GSoC gave me the opportunity to work on it. I like being part of this community. Join us to help to create great Scala tools!</p>
<hr/>
<p/>
<p>Now that the GSoC <a href="http://socghop.appspot.com/document/show/gsoc_program/google/gsoc2010/timeline">‘pencils down’ date</a> has arrived, it is time to report to the community about the achievements of my Scala IDE project. The goal of this project is to provide <a href="http://www.scala-lang.org/gsoc2010">Advanced Semantic Tools for the Scala IDE for Eclipse</a>. </p>
<p>First, I am very appreciative for lots of helpful suggestions, advice and encouragement from my mentor Miles Sabin and other guys in the community. Without their help, it would not have been possible to finish this project.</p>
<p>There is a <a href="http://www.assembla.com/wiki/show/scala-ide/Google_Summer_of_Code">wiki page</a> on the Scala IDE project site which explains some aspects of the features. Let me introduce them by starting with an example code snippet,</p>
<pre>object String2Int {
  val a = "1";
  var b: java.lang.String = "3";
  implicit val somewords = new SomeWords("yeah!")

  implicit def string2Int(s: String) = {
    ((s.toInt)+1)
  }

  def main(args:Array[String]) {
    printInt(string2Int("3"))
    printInt(a+b)
    printIntWithSomeWords("5")(new SomeWords("..."))
    printIntWithSomeWords(2)

    val map = Map( 1 -&gt;"one",2-&gt;"two")
  }

  def printInt(a:Int) {
    println(a)
  }

  def printIntWithSomeWords(a: Int)(implicit sw: SomeWords) {
    println(a)
    println(sw.words)
  }

  class SomeWords(val words: String)
}
</pre>
<p/>
<p>This code stems from an example in <a href="http://www.artima.com/shop/programming_in_scala">Programming in Scala</a>. But I modified it to be “more implicit”.</p>
<p>When you open the editor, all the places where implicit conversions and implicit parameters occur (not the implicit definitions themselves) have been highlighted, as follows,</p>
<p><a href="http://www.scala-ide.org/wp-content/uploads/2010/08/image-01.png"><img alt="Implicit visualization" class="alignleft size-full wp-image-240" height="459" src="http://www.scala-ide.org/wp-content/uploads/2010/08/image-01.png" title="image-01" width="691"/></a></p>
<p>Perhaps you don’t like the default green squiggly underlines as the visual indicator of implicit occurrences? Then you can customize the highlight style via <i>Windows -&gt; Preferences -&gt; Scala -&gt; Editor -&gt; Syntax Coloring</i> as follows,</p>
<p><a href="http://www.scala-ide.org/wp-content/uploads/2010/08/image-02.png"><img alt="Preferences" class="alignleft size-full wp-image-241" height="332" src="http://www.scala-ide.org/wp-content/uploads/2010/08/image-02.png" title="image-02" width="595"/></a></p>
<p>You can hide the highlighting by clearing the checkboxes and setting the underline style to “none”. In future we will add an enable/disable check box to simplify this process.</p>
<p>Along with the visual annotation for implicits, we provide automation around the annotation, known in Eclipse terminology as “quick assists”. The default shortcut for quick assist is “Ctrl+1″. The following screenshot shows the quick assist for an implicit conversion,</p>
<p><a href="http://www.scala-ide.org/wp-content/uploads/2010/08/image-03.png"><img alt="Implicit quick assist" class="alignleft size-full wp-image-242" height="361" src="http://www.scala-ide.org/wp-content/uploads/2010/08/image-03.png" title="image-03" width="530"/></a></p>
<p>After applying this quick assist we get the explicit version of above implicit conversion,</p>
<p><a href="http://www.scala-ide.org/wp-content/uploads/2010/08/image-04.png"><img alt="Inline expansion" class="alignleft size-full wp-image-243" height="69" src="http://www.scala-ide.org/wp-content/uploads/2010/08/image-04.png" title="image-04" width="284"/></a></p>
<p>The following screenshot shows the quick assist for implicit parameters,</p>
<p><a href="http://www.scala-ide.org/wp-content/uploads/2010/08/image-05.png"><img alt="Implicti parameter quick assist" class="alignleft size-full wp-image-244" height="201" src="http://www.scala-ide.org/wp-content/uploads/2010/08/image-05.png" title="image-05" width="580"/></a></p>
<p>After the applying the quick assist, we see the implicit arguments defined in the scope explicitly inlined as follows,</p>
<p><a href="http://www.scala-ide.org/wp-content/uploads/2010/08/image-06.png"><img alt="After inlining" class="alignleft size-full wp-image-245" height="107" src="http://www.scala-ide.org/wp-content/uploads/2010/08/image-06.png" title="image-06" width="348"/></a></p>
<p>One of Scala’s important features is support for type inference. With type inference we are not forced to write many tedious type decorations. However, Scala is a strongly type language and in some contexts it is better to declare the type explicitly, for example method return types.</p>
<p>So we have added functionality which provides explicit type completion, activated automatically by typing “:”. The current implementation is limited to val and method definitions for which the type can be inferred.</p>
<p>The following screenshot shows that I want to add an explicit type for val map. So I type the “:” after the map identifier. Then I get the inferred type quick assist here,</p>
<p><a href="http://www.scala-ide.org/wp-content/uploads/2010/08/image-07.png"><img alt="Inferred type completion" class="alignleft size-full wp-image-246" height="56" src="http://www.scala-ide.org/wp-content/uploads/2010/08/image-07.png" title="image-07" width="434"/></a></p>
<p>When I press Enter, we see the following,</p>
<p><a href="http://www.scala-ide.org/wp-content/uploads/2010/08/image-08.png"><img alt="Inferred type completion after expansion" class="alignleft size-full wp-image-247" height="34" src="http://www.scala-ide.org/wp-content/uploads/2010/08/image-08.png" title="image-08" width="629"/></a></p>
<p>Currently the explicit type is a little long. In future we will allow the qualified part to be moved to the import section.</p>
<p>It is a best practice to add explicit return types for methods (other than for methods which return Unit type). And sometimes you forget to add the “=” when defining a method. This makes the whole method return Unit unfortunately. With our new functionality and that best practice quick assist, you can find and fix this kind of mistake easily. For example, suppose you wanted to add the type for the method by “:” auto-completion. But you find that the proposed type is Unit. Then you will realize that you missed the “=”,</p>
<p><a href="http://www.scala-ide.org/wp-content/uploads/2010/08/image-09.png"><img alt="Inferred return type completion" class="alignleft size-full wp-image-248" height="61" src="http://www.scala-ide.org/wp-content/uploads/2010/08/image-09.png" title="image-09" width="357"/></a></p>
<p>Correct it and add the right type again as follows,</p>
<p><a href="http://www.scala-ide.org/wp-content/uploads/2010/08/image-10.png"><img alt="Inferred return type completion after expansion" class="alignleft size-full wp-image-249" height="61" src="http://www.scala-ide.org/wp-content/uploads/2010/08/image-10.png" title="image-10" width="477"/></a></p>
<p>Adding explicit types for val and method definition is a piece of cake now. In future we will improve explicit type completion to propose types from the classpath if the exact type cannot be inferred.</p>
<p>What do you think about these new features? A build/update site of the GSoC branch will be available shortly and any feedback will be appreciated. When the features has been proven stable, we will merge them into the main distribution. Then everyone can try them out!</p></div>
    </content>
    <updated>2010-08-27T12:16:45Z</updated>
    <published>2010-08-25T19:00:50Z</published>
    <category scheme="http://www.scala-ide.org" term="News"/>
    <author>
      <name>Miles Sabin</name>
      <uri>http://www.scala-ide.org</uri>
    </author>
    <source>
      <id>http://www.scala-ide.org/feed/atom/</id>
      <link href="http://www.scala-ide.org" rel="alternate" type="text/html"/>
      <link href="http://www.scala-ide.org/feed/atom/" rel="self" type="application/atom+xml"/>
      <title xml:lang="en">Scala IDE for Eclipse</title>
      <updated>2010-08-27T12:16:45Z</updated>
    </source>
  </entry>

  <entry xml:lang="en">
    <id>http://www.decodified.com/scala/2010/08/27/scala-rich-wrapping-performance/</id>
    <link href="http://www.decodified.com/scala/2010/08/27/scala-rich-wrapping-performance.html" rel="alternate" type="text/html"/>
    <title>Scala rich wrapping performance</title>
    <summary type="xhtml"><div xmlns="http://www.w3.org/1999/xhtml"><p>Recently I repeatedly found myself wondering whether relying on Scalas rich wrappers for convenience was actually coming with some performance cost or not. Not that it really matters in all but some really time-critical edge cases, however, I remember reading something about modern JVMs being able to completely optimize these wrapping constructs away (by means of so-called “escape analysis”?), so maybe there...</p></div>
    </summary>
    <updated>2010-08-27T07:00:00Z</updated>
    <category scheme="http://www.decodified.com/categories/scala" term="scala"/>
    <source>
      <id>http://www.decodified.com</id>
      <author>
        <name>Mathias</name>
      </author>
      <link href="http://www.decodified.com" rel="alternate" type="text/html"/>
      <link href="http://feeds.feedburner.com/decodified" rel="self" type="application/rss+xml"/>
      <link href="http://pubsubhubbub.appspot.com/" rel="hub" type="text/html"/>
      <rights>Copyright 2010, decodified.com</rights>
      <subtitle>between code and cleartext</subtitle>
      <title>decodified</title>
      <updated>2010-09-03T09:16:29Z</updated>
    </source>
  </entry>

  <entry>
    <id>tag:blogger.com,1999:blog-2726786215957001832.post-8459206366760540625</id>
    <link href="http://www.frothandjava.com/feeds/8459206366760540625/comments/default" rel="replies" type="application/atom+xml"/>
    <link href="https://www.blogger.com/comment.g?blogID=2726786215957001832&amp;postID=8459206366760540625" rel="replies" type="text/html"/>
    <link href="http://www.blogger.com/feeds/2726786215957001832/posts/default/8459206366760540625" rel="edit" type="application/atom+xml"/>
    <link href="http://www.blogger.com/feeds/2726786215957001832/posts/default/8459206366760540625" rel="self" type="application/atom+xml"/>
    <link href="http://www.frothandjava.com/2010/08/google-app-inventor-and-nodejs.html" rel="alternate" type="text/html"/>
    <title>Google App Inventor and node.js</title>
    <content type="xhtml"><div xmlns="http://www.w3.org/1999/xhtml"><div><p>My invite to Google's new, easy to use <a href="http://appinventor.googlelabs.com/about/">App Inventor for Android</a> came through recently and within minutes I had hello world running. Even better, after a few more minutes of playing with the programming toybox I had an easy to use tool.</p><p>For awhile now I've wanted a simple tool that would let me go around scanning the barcodes of books that I own and saving them into a text file for importing into <a href="http://www.librarything.com/">LibraryThing</a> but I haven't had the spare time to learn enough Android programming to build one. A combination of a simple client built with App Inventor and a simple server written with Node and I had the tool I've been wanting in a matter of minutes.</p><p><strong>The AppInventor Client</strong></p><p>AppInventor comes in two parts - an "Interface Builder" website and a visual coding environment where you connect up blocks of code (that sits on top of the Kawa dialect of Scheme - which makes App Inventor coding a lot like a combintation of Lego and Lisp). I quickly added a label (to display the scanned ISBN number), a button (to start the scan) and then two non-visible components: a barcode scanner and a TinyWebDB. Once the UI was done it was off to the coding environment to wire everything up.</p><p>The only not quite straightforward part of all this is the TinyWebDB component as it's App Inventor's only built in way of accesing a web service (other than Twitter, which has it's own component). However, TinyWebDB isn't a generic web service client, it's meant for storing and retreiving simple key/value pairs so I needed to write my server with that in mind.</p><p>As the coding environment is visual, it really doesn't lend itself to a blog post. Fortunately, you can download the app source code in a zip file and marvel at the underlying code. The meat of the app is:</p><pre class="brush: clojure"><br/>&lt;com.google.youngandroid.runtime&gt;;;; Screen1<br/>(do-after-form-creation (set-and-coerce-property! Screen1 'Title "Screen1" 'text)<br/>)<br/>;;; Label1<br/>(add-component Screen1 Label Label1 (set-and-coerce-property! Label1 'Text "Text for Label1" 'text)<br/>)<br/>;;; Button1<br/>(add-component Screen1 Button Button1 (set-and-coerce-property! Button1 'Text "Scan" 'text)<br/>)<br/>(define-event Button1 Click()<br/>(call-component-method 'BarcodeScanner1 'DoScan (list)<br/>*no-coercion*)<br/><br/>)<br/>;;; BarcodeScanner1<br/>(add-component Screen1 BarcodeScanner BarcodeScanner1 )<br/>(define-event BarcodeScanner1 AfterScan( result )<br/>(call-component-method 'TinyWebDB1 'StoreValue (list "isbn" (get-property BarcodeScanner1 Result)<br/>)<br/>'( text any)<br/>)<br/><br/>(set-and-coerce-property! Label1 'Text (get-property BarcodeScanner1 Result)<br/>'text)<br/><br/>)<br/>;;; TinyWebDB1<br/>(add-component Screen1 TinyWebDB TinyWebDB1 (set-and-coerce-property! TinyWebDB1 'ServiceURL "http://192.168.1.101:8765" 'text)<br/>)<br/>(init-runtime  #f)<br/>&lt;/com.google.youngandroid.runtime&gt;</pre><br/>While that's not quite the entire source, it does give some idea of what goes on underneath.<br/><br/><span style="font-weight: bold;">Node(.js)</span><br/><br/>TinyWebDB will post a key/value pair to whatever server you want. So I needed a simple server that would sit there, extract the value and output to stdout (which will then get piped into a file). This seemed like the perfect opportunity to try Node (I can't tell if it's supposed to be called node or node.js), which is a Javascript execution environment based on the V8 engine for writing network programs. A quick and dirty Javascript hack produced:<br/><pre class="brush: js"><br/>var http = require('http');<br/>http.createServer(function (request, response) {<br/>request.on('data', function(chunk) {<br/>    var b = chunk.toString('ascii', 0, chunk.length);<br/>    var v = b.split("&amp;")[1];<br/>    var vv = v.split("=")[1];<br/>    var vvv = vv.replace("%22", "");<br/>    var vvvv = vvv.replace("%22", "");<br/>    console.log(vvvv);<br/>});<br/>response.writeHead(200, {'Content-Type': 'text/plain'});<br/>response.end('Hello, World\n');<br/>}).listen(8765);<br/></pre><br/><br/><p>Undoubtedly a regexp could have been used, but would have required more mental effort than I really wanted. In case you're wondering about the response, TinyWebDB apparently essentially disregards it, so sending back Hello, World doesn't hurt.<br/></p><span style="font-weight: bold;">Conclusion</span><br/><br/>In a matter of minutes I had a useful (at least to me) tool. I have a feeling that this is what App Inventor will mostly be used for - simple apps that satisfy a single person's needs. It's not going cause the "Animated Cat App Apocalypse" in the Android Market that some commentators have worried about. I have no idea if it will be of any use as the "Logo for the modern age" that was the original reason for it's existence (there are still references to "Young Android" in the generated code and the application icons are of an adult and child robot). I would call it the "Visual Basic for the modern age" except that it feels wrong comparing something that "<span style="font-style: italic;">is part of an ongoing movement in computers and education that began with the work of Seymour Papert and the MIT Logo Group in the 1960s</span>" with Visual Basic.<br/></div><div class="blogger-post-footer"><img alt="" height="1" src="https://blogger.googleusercontent.com/tracker/2726786215957001832-8459206366760540625?l=www.frothandjava.com" width="1"/></div></div>
    </content>
    <updated>2010-08-26T23:04:18Z</updated>
    <published>2010-08-26T21:48:00Z</published>
    <author>
      <name>Scot McSweeney-Roberts</name>
      <email>noreply@blogger.com</email>
      <uri>http://www.blogger.com/profile/05078277004789544258</uri>
    </author>
    <source>
      <id>tag:blogger.com,1999:blog-2726786215957001832</id>
      <author>
        <name>Scot McSweeney-Roberts</name>
        <email>noreply@blogger.com</email>
        <uri>http://www.blogger.com/profile/05078277004789544258</uri>
      </author>
      <link href="http://www.frothandjava.com/feeds/posts/default" rel="http://schemas.google.com/g/2005#feed" type="application/atom+xml"/>
      <link href="http://www.blogger.com/feeds/2726786215957001832/posts/default" rel="self" type="application/atom+xml"/>
      <link href="http://www.frothandjava.com/" rel="alternate" type="text/html"/>
      <link href="http://pubsubhubbub.appspot.com/" rel="hub" type="text/html"/>
      <link href="http://www.blogger.com/feeds/2726786215957001832/posts/default?start-index=26&amp;max-results=25" rel="next" type="application/atom+xml"/>
      <subtitle>Java, Groovy, Scala, Etc</subtitle>
      <title>Froth &amp; Java</title>
      <updated>2010-08-26T23:04:18Z</updated>
    </source>
  </entry>

  <entry>
    <id>http://code.technically.us/post/1014215544</id>
    <link href="http://code.technically.us/post/1014215544" rel="alternate" type="text/html"/>
    <title>"On the other hand, because many of Scala’s concepts are very general and orthogonal, they can be..."</title>
    <summary type="xhtml"><div xmlns="http://www.w3.org/1999/xhtml">“On the other hand, because many of Scala’s concepts are very general and orthogonal, they can be combined in a large number of ways. So it is indeed true that almost anything can be achieved in different ways in Scala. It takes practice to discover that often some ways are preferable to others. And it takes a certain amount of tolerance to accept that sometimes there’s more than one route to a good design.”<br/><br/> - <em><a href="http://lamp.epfl.ch/~odersky/blogs/isscalacomplex.html">Simple or Complex?</a></em></div>
    </summary>
    <updated>2010-08-26T13:10:37Z</updated>
    <category term="Scala"/>
    <category term="Complexity"/>
    <category term="Orthogonality"/>
    <category term="Software"/>
    <category term="Design"/>
    <category term="Odersky"/>
    <source>
      <id>http://code.technically.us/</id>
      <author>
        <name>Coderspiel</name>
      </author>
      <link href="http://tumblr.superfeedr.com/" rel="hub" type="text/html"/>
      <link href="http://code.technically.us/" rel="alternate" type="text/html"/>
      <link href="http://code.technically.us/rss" rel="self" type="application/rss+xml"/>
      <title>Coderspiel</title>
      <updated>2010-09-09T03:00:39Z</updated>
    </source>
  </entry>

  <entry>
    <id>tag:blogger.com,1999:blog-19725519.post-1452176707084833322</id>
    <link href="http://erikengbrecht.blogspot.com/2010/08/scala-is-for-vb-programmers.html" rel="alternate" type="text/html"/>
    <title>Scala is for VB programmers</title>
    <summary type="xhtml"><div xmlns="http://www.w3.org/1999/xhtml"><p>
Normally I don't go for flame bait titles.  But I haven't finished my morning coffee yet so I can't help myself.  There's once again a debate raging across the internet about whether Scala is more or less complex than Java, along with the more nuanced argument that yes, it is more complex but only framework and library developers have to contend with this complexity.  This argument usually happens when someone <a href="http://java.dzone.com/articles/scala-complex-yes-and">posts a little bit of code like this</a>:
</p>
<pre>def map[B, That](f: A =&gt; B)(implicit bf: CanBuildFrom[Repr, B, That]): That
</pre>
<p>
And then someone responds <a href="http://warpedjavaguy.wordpress.com/2010/08/02/the-scala-is-too-complex-conspiracy-1/#comment-400">like this:</a>
</p>
<blockquote>
Why do not people realize that Java is too difficult for the average programmer? That is the true purpose of Scala, to escape the complexity of Java code!

Framework code in Scala, with heavy use of implicit keywords and all kinds of type abstractions, is very difficult. This is correct, but this code is not meant for innocent eyes. You do not use that sort of code when you write an application.
</blockquote>
<p>
I've seen this type of thinking before.  A few years ago I had a bout of insanity and lead an ASP.NET project using ASP.NET 2.0.  I had no .NET experience prior to this project.  The project failed, although the reasons for that failure are legion and unimportant here.  But I noticed something about ASP.NET developers: they have no clue how the technology works.  It's a black box.  Do you why?  Because it <b>is</b> a black box.  I searched and searched and couldn't even find a good illustration of the lifecycle for an ASP.NET page that's using events.  This type of information is put front and center in the Java world.  It's absolutely buried in the Microsoft world.  Or at least the parts of it that target the hoards of VB programmers that are undyingly loyal to MS.  The framework is magic dust created by the great wizards in Redmond so that you can build solutions for your customers.  Do not question the dust.  Think about VB.  Or, no don't, it might damage your brain.  My coffee hasn't quite kicked in, so I should have some immunity, so I'll do it for you.  VB is a black box (well, at old school VB6).  It was designed to allow people who do not know how to really program, and who will probably never know how to program, to create applications.  It's completely flat, opaque abstraction.  The dichotomy between the application developer and the framework developer is as high and as thick as the gates of Mordor.
</p>
<p>
There are many people in the Scala community that claim Scala's complexity can be hidden from the application program.  I don't believe them, but there's a chance that they are right.   It's technically feasible, and I can see how it could happen if Scala started attracting lots of VB programmers.  I can't see how it's going to attract lots of VB programmers, but apparently many people in the Scala community think Scala is for VB programmers.  So we'll just have to wait and see...
</p><div class="blogger-post-footer"><img alt="" height="1" src="https://blogger.googleusercontent.com/tracker/19725519-1452176707084833322?l=erikengbrecht.blogspot.com" width="1"/></div></div>
    </summary>
    <updated>2010-08-26T11:44:00Z</updated>
    <category scheme="http://www.blogger.com/atom/ns#" term="Scala"/>
    <category scheme="http://www.blogger.com/atom/ns#" term="Java"/>
    <category scheme="http://www.blogger.com/atom/ns#" term="programming"/>
    <category scheme="http://www.blogger.com/atom/ns#" term="microsoft"/>
    <author>
      <name>Erik Engbrecht</name>
      <email>noreply@blogger.com</email>
    </author>
    <source>
      <id>tag:blogger.com,1999:blog-19725519</id>
      <author>
        <name>Erik Engbrecht</name>
        <email>noreply@blogger.com</email>
      </author>
      <link href="http://erikengbrecht.blogspot.com/" rel="alternate" type="text/html"/>
      <link href="http://erikengbrecht.blogspot.com/feeds/posts/default?alt=rss" rel="self" type="application/atom+xml"/>
      <subtitle>Thoughts and Essays on Systems Engineering and Software Engineering,  and IT</subtitle>
      <title>Erik Engbrecht's Blog</title>
      <updated>2010-09-08T02:00:45Z</updated>
    </source>
  </entry>

  <entry xml:lang="en">
    <id>http://www.scala-lang.org/7431 at http://www.scala-lang.org</id>
    <link href="http://www.scala-lang.org/node/7431" rel="alternate" type="text/html"/>
    <title>Simple or Complicated?</title>
    <summary type="xhtml"><div xmlns="http://www.w3.org/1999/xhtml"><p><span style="font-family: Arial;">Recently we have seen a heated debate on whether Scala is too complicated for normal programmers or whether it’s in fact a rather simple language to program in. Here are two <a href="http://michid.wordpress.com/">representative</a> <a href="http://warpedjavaguy.wordpress.com/2010/08/02/the-scala-is-too-complex-conspiracy-1/">blogposts</a> of the debate. The comments on the posts are also worth reading.</span><span style="font-family: Arial;"> I have written up <a href="http://lamp.epfl.ch/~odersky/blogs/isscalacomplex.html">some thoughts here</a>.</span></p>  <p class="MsoNormal"><span style="font-family: Arial;">&lt;o:p&gt; &lt;/o:p&gt;</span></p></div>
    </summary>
    <updated>2010-08-26T10:28:04Z</updated>
    <author>
      <name>odersky</name>
    </author>
    <source>
      <id>http://www.scala-lang.org/</id>
      <link href="http://www.scala-lang.org/" rel="alternate" type="text/html"/>
      <link href="http://www.scala-lang.org/rss.xml" rel="self" type="application/rss+xml"/>
      <title>The Scala Programming Language</title>
      <updated>2010-09-09T03:01:10Z</updated>
    </source>
  </entry>

  <entry>
    <id>tag:blogger.com,1999:blog-8932258692847145228.post-1807202799863175916</id>
    <link href="http://thecarefulprogrammer.blogspot.com/feeds/1807202799863175916/comments/default" rel="replies" type="application/atom+xml"/>
    <link href="https://www.blogger.com/comment.g?blogID=8932258692847145228&amp;postID=1807202799863175916" rel="replies" type="text/html"/>
    <link href="http://www.blogger.com/feeds/8932258692847145228/posts/default/1807202799863175916" rel="edit" type="application/atom+xml"/>
    <link href="http://www.blogger.com/feeds/8932258692847145228/posts/default/1807202799863175916" rel="self" type="application/atom+xml"/>
    <link href="http://thecarefulprogrammer.blogspot.com/2010/08/from-clojure-to-ruby.html" rel="alternate" type="text/html"/>
    <title>From Clojure to Ruby</title>
    <content type="xhtml"><div xmlns="http://www.w3.org/1999/xhtml">Ever since I've received <a href="http://pragprog.com/titles/shcloj/programming-clojure">Stuart Halloway's Programming Clojure</a>, I've been reading, watching and listening about <a href="http://clojure.org/">Clojure</a>. And dabbling with it a little.<br/><br/>A few months ago, I started learning Ruby. My main learning experience has been <a href="http://book.rubylearning.org/">The Ultimate Book to Ruby Programming</a> by <a href="http://satishtalim.com/">Satish Talim</a> and his <a href="http://www.rubylearning.org/">free online class Core Ruby</a>.<br/><br/>I just finished the Core Ruby Class 18th batch and I must say it's excellent. The class material not only makes a good introduction, it's also my first reference for looking up core concepts. The class ran for 8 weeks. At first, I thought that was too long to cover the basics, but if you do have a day job, the class will be taking plenty of evening and weekend study time.<br/><br/>Each week has assigned reading materials, exercises and a quiz. To really get more from the class than you'd get from just reading a book, you have to do the exercises, post your solutions, discuss them and read solutions from others. The class have competent and friendly mentors that will really help you get from a "Classic OO language in Ruby" solution to an idiomatic Ruby solution. I've also had the chance to have good classmates.<br/><br/>I must stress the point that you can only get back from the class as much as you invest yourself in it. Workload would vary from week to week, but I consider 5 hours a week an absolute minimum and 10 hours is better.  I've once spent 8 hours just on a bonus exercise (The <a href="http://en.wikipedia.org/wiki/Playfair_cipher">Playfair Cypher</a>, if you must know.)  YMMV of course!<br/><br/>The bottom line is if you're serious about learning Ruby and you're ready to put in the hours and your passion, the Core Ruby Class is an excellent way to start your journey.<br/><br/>Going back to Clojure, I got some advantages from learning it that translate to Ruby since they have some things in common.<br/><br/>The first thing I noticed is both languages use keywords and with the same syntax too! Hello, I'm a <span style="font-weight: bold; font-style: italic;">:</span><span style="font-style: italic;">keyword</span>.<br/><br/>Keywords can be seen as a way to use strings as constants. The advantage over using normal strings is two symbols with the same name are guaranteed to be the same object and thus, you can compare using reference equality instead of value equality. It's typical to use keywords for hash keys. It took me a while to wrap my head around the keyword concept in Clojure, so I was glad to be able recycle it.<br/><br/>Another common thing is the use of separators instead of camel cases for variable and function names: <span style="font-style: italic;">encrypt_message</span> in Ruby or <span style="font-style: italic;">encrypt-message</span> in Clojure. Also, putting ! or ? at the end of the function to express mutation or a predicate. Example: <span style="font-style: italic;">"Hello".empty?</span> in Ruby or <span style="font-style: italic;">(empty? "Hello")</span> in Clojure. Funnily enough, I'm testing these examples with <a href="http://redcareditor.com/">Redcar</a>, a Ruby editor running on JRuby featuring both a Ruby and a Clojure REPL.<br/><br/>As for conditional testing, Ruby and Clojure considers false and nil to be false, and everything else to be true.<br/><br/>Well, there are plenty of differences too of course and I got bitten more than once. They say when you learn your third spoken languages that you'll mix it up with your second spoken language at first. Likewise, even though one is a Lisp dialect and the other one isn't, more often than not, I'll declare a Ruby function like this:<br/><span style="font-style: italic;">def repeat_function some_function time_interval total_interval do...</span><br/><br/>I forget the commas between the arguments.<br/><br/>Strange, but true.<div class="blogger-post-footer"><img alt="" height="1" src="https://blogger.googleusercontent.com/tracker/8932258692847145228-1807202799863175916?l=thecarefulprogrammer.blogspot.com" width="1"/></div></div>
    </content>
    <updated>2010-08-26T02:53:32Z</updated>
    <published>2010-08-26T01:26:00Z</published>
    <category scheme="http://www.blogger.com/atom/ns#" term="clojure ruby rubylearning.com"/>
    <author>
      <name>The Careful Programmer</name>
      <email>noreply@blogger.com</email>
      <uri>http://www.blogger.com/profile/13075337864712215296</uri>
    </author>
    <source>
      <id>tag:blogger.com,1999:blog-8932258692847145228</id>
      <author>
        <name>The Careful Programmer</name>
        <email>noreply@blogger.com</email>
        <uri>http://www.blogger.com/profile/13075337864712215296</uri>
      </author>
      <link href="http://thecarefulprogrammer.blogspot.com/feeds/posts/default" rel="http://schemas.google.com/g/2005#feed" type="application/atom+xml"/>
      <link href="http://www.blogger.com/feeds/8932258692847145228/posts/default" rel="self" type="application/atom+xml"/>
      <link href="http://thecarefulprogrammer.blogspot.com/" rel="alternate" type="text/html"/>
      <link href="http://pubsubhubbub.appspot.com/" rel="hub" type="text/html"/>
      <subtitle>Programming pondering.</subtitle>
      <title>The Careful Programmer</title>
      <updated>2010-08-26T18:03:49Z</updated>
    </source>
  </entry>

  <entry xml:lang="en">
    <id>http://michid.wordpress.com/?p=230</id>
    <link href="http://michid.wordpress.com/2010/08/24/so-scala-is-too-complex/" rel="alternate" type="text/html"/>
    <title>So Scala is too complex?</title>
    <summary type="xhtml"><div xmlns="http://www.w3.org/1999/xhtml">There is currently lots of talk about Scala being to complex. Instead of more arguing I implemented the same bit of functionality in Scala and in Java and let everyone decide for themselves. There is some nice example code in the manual to the The Scala 2.8 Collections API which partitions a list of persons [...]<img alt="" border="0" height="1" src="http://stats.wordpress.com/b.gif?host=michid.wordpress.com&amp;blog=2538862&amp;post=230&amp;subd=michid&amp;ref=&amp;feed=1" width="1"/></div>
    </summary>
    <content type="xhtml"><div xmlns="http://www.w3.org/1999/xhtml"><p>There is currently <a href="http://warpedjavaguy.wordpress.com/2010/08/02/the-scala-is-too-complex-conspiracy-1/">lots of talk</a> about <a href="http://www.scala-lang.org/">Scala</a> being to complex. Instead of more arguing I implemented the same bit of functionality in Scala and in Java and let everyone decide for themselves. </p>
<p>There is some nice example code in the manual to the <a href="http://lampwww.epfl.ch/~odersky/whatsnew/collections-api/collections.html">The Scala 2.8 Collections API</a> which partitions a list of persons into two lists of minors and majors. Below are the fleshed out implementations in Scala and Java.</p>
<p>First Scala:</p>
<pre class="brush: java;">object ScalaMain {
  case class Person(name: String, age: Int)

  val persons = List(
    Person("Boris", 40),
    Person("Betty", 32),
    Person("Bambi", 17))

  val (minors, majors) = persons.partition(_.age &lt;= 18) 

  def main(args: Array[String]) = {
    println (minors.mkString(", "))
    println (majors.mkString(", "))
  }
}
</pre>
<p>And now Java:</p>
<pre class="brush: java;">import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

class Person {
    private final String name;
    private final int age;

    public Person(String name, int age) {
        super();
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

    @Override
    public boolean equals(Object other) {
        if (this == other) {
            return true;
        }
        else if (other instanceof Person) {
            Person p = (Person) other;
            return name == null ? p.name == null : name.equals(p.name)
                    &amp;&amp; age == p.age;

        }
        else {
            return false;
        }
    }

    @Override
    public int hashCode() {
        int h = name == null ? 0 : name.hashCode();
        return 39*h + age;
    }

    @Override
    public String toString() {
        return new StringBuilder("Person(")
            .append(name).append(",")
            .append(age).append(")").toString();
    }
}

public class JavaMain {

    private final static List&lt;Person&gt; persons = Arrays.asList(
        new Person("Boris", 40),
        new Person("Betty", 32),
        new Person("Bamby", 17));

    private static List&lt;Person&gt; minors = new ArrayList&lt;Person&gt;();
    private static List&lt;Person&gt; majors = new ArrayList&lt;Person&gt;();

    public static void main(String[] args) {
        partition(persons, minors, majors);
        System.out.println(mkString(minors, ","));
        System.out.println(mkString(majors, ","));
    }

    private static void partition(List&lt;? extends Person&gt; persons,
            List&lt;? super Person&gt; minors, List&lt;? super Person&gt; majors) {

        for (Person p : persons) {
            if (p.getAge() &lt;= 18) minors.add(p);
            else majors.add(p);
        }
    }

    private static &lt;T&gt; String mkString(List&lt;T&gt; list, String separator) {
        StringBuilder s = new StringBuilder();
        Iterator&lt;T&gt; it = list.iterator();
        if (it.hasNext()) {
            s.append(it.next());
        }
        while (it.hasNext()) {
            s.append(separator).append(it.next());
        }
        return s.toString();
    }

}
</pre>
<p>Impressive huh? And the Java version is not even entirely correct since its equals() method might not cope correctly with super classes of Person.</p>
<br/>Filed under: <a href="http://michid.wordpress.com/category/uncategorized/">Uncategorized</a> Tagged: <a href="http://michid.wordpress.com/tag/java/">Java</a>, <a href="http://michid.wordpress.com/tag/scala/">Scala</a> <a href="http://feeds.wordpress.com/1.0/gocomments/michid.wordpress.com/230/" rel="nofollow"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/michid.wordpress.com/230/"/></a> <a href="http://feeds.wordpress.com/1.0/godelicious/michid.wordpress.com/230/" rel="nofollow"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/michid.wordpress.com/230/"/></a> <a href="http://feeds.wordpress.com/1.0/gofacebook/michid.wordpress.com/230/" rel="nofollow"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/michid.wordpress.com/230/"/></a> <a href="http://feeds.wordpress.com/1.0/gotwitter/michid.wordpress.com/230/" rel="nofollow"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/michid.wordpress.com/230/"/></a> <a href="http://feeds.wordpress.com/1.0/gostumble/michid.wordpress.com/230/" rel="nofollow"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/michid.wordpress.com/230/"/></a> <a href="http://feeds.wordpress.com/1.0/godigg/michid.wordpress.com/230/" rel="nofollow"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/michid.wordpress.com/230/"/></a> <a href="http://feeds.wordpress.com/1.0/goreddit/michid.wordpress.com/230/" rel="nofollow"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/michid.wordpress.com/230/"/></a> <img alt="" border="0" height="1" src="http://stats.wordpress.com/b.gif?host=michid.wordpress.com&amp;blog=2538862&amp;post=230&amp;subd=michid&amp;ref=&amp;feed=1" width="1"/></div>
    </content>
    <updated>2010-08-24T21:04:04Z</updated>
    <category term="Uncategorized"/>
    <category term="Java"/>
    <category term="Scala"/>
    <author>
      <name>michid</name>
    </author>
    <source>
      <id>http://michid.wordpress.com</id>
      <logo>http://0.gravatar.com/blavatar/8a44e33f0c0b6ba0377f3633082fb84d?s=96&amp;d=http://s2.wp.com/i/buttonw-com.png</logo>
      <link href="http://michid.wordpress.com/feed/" rel="self" type="application/atom+xml"/>
      <link href="http://michid.wordpress.com" rel="alternate" type="text/html"/>
      <link href="http://michid.wordpress.com/osd.xml" rel="search" type="application/opensearchdescription+xml"/>
      <link href="http://michid.wordpress.com/?pushpress=hub" rel="hub" type="text/html"/>
      <subtitle>Hacking Scala</subtitle>
      <title>Michid's Weblog</title>
      <updated>2010-09-09T03:00:37Z</updated>
    </source>
  </entry>

  <entry xml:lang="en">
    <id>http://codemonkeyism.com/?p=1964</id>
    <link href="http://feedproxy.google.com/~r/stephansblog/~3/ECOapqbOBBs/" rel="alternate" type="text/html"/>
    <link href="http://codemonkeyism.com/interface-implementation-depedencies-java/#comments" rel="replies" type="text/html"/>
    <link href="http://codemonkeyism.com/interface-implementation-depedencies-java/feed/atom/" rel="replies" type="application/atom+xml"/>
    <title xml:lang="en">Interface vs. Implementation Dependencies in Java</title>
    <summary type="xhtml" xml:lang="en"><div xmlns="http://www.w3.org/1999/xhtml">I often use the notion of interface and implementation dependencies, where interface dependencies are mostly always smaller. I think this is a very important concept to understand for Java developers, and although it seems obvious and self evident, many developers do not think along those lines and still couple classes too tightly.
Take this example:

class CassandraStorage [...]<img height="1" src="http://feeds.feedburner.com/~r/stephansblog/~4/ECOapqbOBBs" width="1"/></div>
    </summary>
    <updated>2010-08-24T14:58:27Z</updated>
    <published>2010-08-24T14:46:22Z</published>
    <category scheme="http://codemonkeyism.com" term="Java"/><feedburner:origLink xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0">http://codemonkeyism.com/interface-implementation-depedencies-java/</feedburner:origLink>
    <author>
      <name>stephan</name>
      <uri>http://codemonkeyism.com</uri>
    </author>
    <source>
      <id>http://codemonkeyism.com/feed/atom/</id>
      <link href="http://codemonkeyism.com" rel="alternate" type="text/html"/>
      <link href="http://feeds.feedburner.com/stephansblog" rel="self" type="application/atom+xml"/>
      <link href="http://pubsubhubbub.appspot.com/" rel="hub" type="text/html"/>
      <title xml:lang="en">Code Monkeyism</title>
      <updated>2010-09-08T05:05:52Z</updated>
    </source>
  </entry>

  <entry>
    <id>tag:blogger.com,1999:blog-7317245822288637185.post-1525784345068910091</id>
    <link href="http://grahamhackingscala.blogspot.com/feeds/1525784345068910091/comments/default" rel="replies" type="application/atom+xml"/>
    <link href="http://grahamhackingscala.blogspot.com/2010/08/intentional-programming-intellij-idea.html#comment-form" rel="replies" type="text/html"/>
    <link href="http://www.blogger.com/feeds/7317245822288637185/posts/default/1525784345068910091?v=2" rel="edit" type="application/atom+xml"/>
    <link href="http://www.blogger.com/feeds/7317245822288637185/posts/default/1525784345068910091?v=2" rel="self" type="application/atom+xml"/>
    <link href="http://feedproxy.google.com/~r/blogspot/vnby/~3/cYjshd1AsUY/intentional-programming-intellij-idea.html" rel="alternate" type="text/html"/>
    <title>Things I Love About IntelliJ IDEA: Smart Intentional Programming Support</title>
    <content type="xhtml"><div xmlns="http://www.w3.org/1999/xhtml">Intentional Programming or "Coding by Intention" is a style of code authoring where, rather than creating low-level parts of code (the building blocks) and then writing the higher-level code (the orchestrators) to bring it together afterwards, you start by writing the high-level code, referencing methods and data that don't yet exist, building up a complete view of the big picture, and then implement the lower-level functions needed to make the big picture work. The main benefit, as you can probably see from my description, is that you get the big picture right and then shape the details to fit, rather than getting the details "right" and then making the big picture fit. **<br/><br/>IntelliJ IDEA has always had great support for coding by intention. It was one of the first 'wow' moments I had when I started using it in the early 00s. Some people have probably never coded without automatic importing, but for those of us who had, the pop-up question "Do you want to import java.util.Properties?" was like black magic. The ability to create a method based on a sample invocation was also in IntelliJ from the very early on, and it was quite revolutionary at the time.<br/><br/>What I love about IntelliJ's intentions is that they really do make the product seem intelligent. You get the impression that the IDE knows just as much about your code as you do, perhaps even more. A great example of this is if you use intentional programming to put() an entry into a non-existent Map and then use IDEA's 'Create Field' intention to create the map.<br/><br/><a href="http://1.bp.blogspot.com/_CwSjmZq5D1I/THPM1M_jXJI/AAAAAAAAACc/OtChSfxAPwI/s1600/IDEA+Screenshot1.png"><img alt="" border="0" id="BLOGGER_PHOTO_ID_5508971983597165714" src="http://1.bp.blogspot.com/_CwSjmZq5D1I/THPM1M_jXJI/AAAAAAAAACc/OtChSfxAPwI/s400/IDEA+Screenshot1.png" style="cursor: pointer; width: 400px; height: 230px;"/></a><br/><br/>IDEA guesses (based on the fact that you are invoking a method called put() with two arguments) that maybe the field you want to create is a Map, so it makes that its first suggestion. But it also goes the extra step of suggesting type arguments for the K and V parameters on the Map interface that match the argument types in your intentional code, so that the whole type declaration will be complete simply by your pressing Enter.<br/><br/><a href="http://3.bp.blogspot.com/_CwSjmZq5D1I/THPM1ijDXfI/AAAAAAAAACk/0QQY0voZlPA/s1600/IDEA+Screenshot2.png"><img alt="" border="0" id="BLOGGER_PHOTO_ID_5508971989383208434" src="http://3.bp.blogspot.com/_CwSjmZq5D1I/THPM1ijDXfI/AAAAAAAAACk/0QQY0voZlPA/s400/IDEA+Screenshot2.png" style="cursor: pointer; width: 400px; height: 265px;"/></a><br/><br/>Seeing as I've described how IDEA figures this out, it doesn't seem all that magical, but it's actually really useful. IDEA saves you from having to type nearly anything about the new field except perhaps to initialise it with a suitable Map implementation, <a href="http://feeds.feedburner.com/2010/08/intellij-idea-smart-auto-completion.html" target="_blank">which is actually just as easy as typing "new " and then hitting Ctrl-Shift-Space</a>.<br/><br/>So, what if you try the same trick with Eclipse?<br/>Eclipse has intentions, but compared to IDEA they're kind of brain-dead…<br/><br/><a href="http://4.bp.blogspot.com/_CwSjmZq5D1I/THPM2Z5VvfI/AAAAAAAAACs/MV0FtHutQYY/s1600/Eclipse+Screenshot.png"><img alt="" border="0" id="BLOGGER_PHOTO_ID_5508972004240637426" src="http://4.bp.blogspot.com/_CwSjmZq5D1I/THPM2Z5VvfI/AAAAAAAAACs/MV0FtHutQYY/s400/Eclipse+Screenshot.png" style="cursor: pointer; width: 400px; height: 248px;"/></a><br/><br/>So Eclipse will make you a field with the right name, but it just declares it with a type of Object. So you have to go up the top and type in the type that you actually want to use, including the type parameters for a Map, yourself. Is that really intentional programming, or does it just save you from copy-pasting the field name?<br/><br/>Another example of IDEA's type-aware goodness can be seen by comparing the expansion of IDEA's "iter" template with Eclipse's "fore" template. Both produce the same Java 5 for-each loop, but IDEA's combination of type-aware template completion and smart name suggesting results in far less typing than the corresponding Eclipse template.<br/><br/>The JetBrains guys are so mad about intentional programming that they've <a href="http://www.jetbrains.com/idea/documentation/intentions.jsp" target="_blank">dedicated a whole page of their documentation to showing of their many "intentions"</a>.<br/><br/>** If you want to, you can <a href="http://clintshank.javadevelopersjournal.com/coding_by_intention.htm" target="_blank">read more about coding by intention here</a><div class="blogger-post-footer"><img alt="" height="1" src="https://blogger.googleusercontent.com/tracker/7317245822288637185-1525784345068910091?l=grahamhackingscala.blogspot.com" width="1"/></div>
<p><a href="http://feedads.g.doubleclick.net/~a/DXJPGTxLaB6pKo6X59OJcEXvtAM/0/da"><img border="0" ismap="true" src="http://feedads.g.doubleclick.net/~a/DXJPGTxLaB6pKo6X59OJcEXvtAM/0/di"/></a><br/>
<a href="http://feedads.g.doubleclick.net/~a/DXJPGTxLaB6pKo6X59OJcEXvtAM/1/da"><img border="0" ismap="true" src="http://feedads.g.doubleclick.net/~a/DXJPGTxLaB6pKo6X59OJcEXvtAM/1/di"/></a></p><img height="1" src="http://feeds.feedburner.com/~r/blogspot/vnby/~4/cYjshd1AsUY" width="1"/></div>
    </content>
    <updated>2010-08-24T14:01:12Z</updated>
    <published>2010-08-24T13:40:00Z</published>
    <category scheme="http://www.blogger.com/atom/ns#" term="intellij"/>
    <category scheme="http://www.blogger.com/atom/ns#" term="eclipse"/>
    <category scheme="http://www.blogger.com/atom/ns#" term="intelligent"/>
    <category scheme="http://www.blogger.com/atom/ns#" term="compare"/>
    <category scheme="http://www.blogger.com/atom/ns#" term="comparison"/>
    <category scheme="http://www.blogger.com/atom/ns#" term="idea"/>
    <category scheme="http://www.blogger.com/atom/ns#" term="jetbrains"/>
    <category scheme="http://www.blogger.com/atom/ns#" term="smart"/>
    <category scheme="http://www.blogger.com/atom/ns#" term="type-aware"/>
    <category scheme="http://www.blogger.com/atom/ns#" term="intentional"/>
    <category scheme="http://www.blogger.com/atom/ns#" term="programming"/>
    <category scheme="http://www.blogger.com/atom/ns#" term="magic"/>
    <category scheme="http://www.blogger.com/atom/ns#" term="coding"/><feedburner:origLink xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0">http://grahamhackingscala.blogspot.com/2010/08/intentional-programming-intellij-idea.html</feedburner:origLink>
    <author>
      <name>Grazer</name>
      <email>noreply@blogger.com</email>
      <uri>http://www.blogger.com/profile/00435359638152521056</uri>
    </author>
    <source>
      <id>tag:blogger.com,1999:blog-7317245822288637185</id>
      <author>
        <name>Grazer</name>
        <email>noreply@blogger.com</email>
        <uri>http://www.blogger.com/profile/00435359638152521056</uri>
      </author>
      <link href="http://grahamhackingscala.blogspot.com/feeds/posts/default" rel="http://schemas.google.com/g/2005#feed" type="application/atom+xml"/>
      <link href="http://grahamhackingscala.blogspot.com/" rel="alternate" type="text/html"/>
      <link href="http://feeds.feedburner.com/blogspot/vnby" rel="self" type="application/atom+xml"/>
      <link href="http://pubsubhubbub.appspot.com/" rel="hub" type="text/html"/>
      <subtitle>The point of "Graham Hacking Scala" is to share with you my knowledge of and experience with the Scala programming language. The blog will contain everything from introductions to basic features through to in-depth analysis of complex techniques and problems. When I make mistakes, you will learn from my mistakes. When I discover cool features, you will learn about them, too.</subtitle>
      <title>Graham Hacking Scala</title>
      <updated>2010-09-04T16:58:00Z</updated>
    </source>
  </entry>

  <entry xml:lang="en">
    <id>http://codemonkeyism.com/?p=1947</id>
    <link href="http://feedproxy.google.com/~r/stephansblog/~3/kohg4eR7las/" rel="alternate" type="text/html"/>
    <link href="http://codemonkeyism.com/singletons-singletons-scala-type-classes/#comments" rel="replies" type="text/html"/>
    <link href="http://codemonkeyism.com/singletons-singletons-scala-type-classes/feed/atom/" rel="replies" type="application/atom+xml"/>
    <title xml:lang="en">Singletons without Singletons: Scala Type Classes</title>
    <summary type="xhtml" xml:lang="en"><div xmlns="http://www.w3.org/1999/xhtml">I was using Guice in a project recently. Objects which did not come out of Guice got their dependencies not injected. So I had a global singleton where objects could get their dependencies. Yeah yeah I know singletons are bad and stuff. It would be nicer to let Guice handle it all, but sometimes this [...]<img height="1" src="http://feeds.feedburner.com/~r/stephansblog/~4/kohg4eR7las" width="1"/></div>
    </summary>
    <updated>2010-08-23T15:07:04Z</updated>
    <published>2010-08-23T15:01:53Z</published>
    <category scheme="http://codemonkeyism.com" term="Java"/><feedburner:origLink xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0">http://codemonkeyism.com/singletons-singletons-scala-type-classes/</feedburner:origLink>
    <author>
      <name>stephan</name>
      <uri>http://codemonkeyism.com</uri>
    </author>
    <source>
      <id>http://codemonkeyism.com/feed/atom/</id>
      <link href="http://codemonkeyism.com" rel="alternate" type="text/html"/>
      <link href="http://feeds.feedburner.com/stephansblog" rel="self" type="application/atom+xml"/>
      <link href="http://pubsubhubbub.appspot.com/" rel="hub" type="text/html"/>
      <title xml:lang="en">Code Monkeyism</title>
      <updated>2010-09-08T05:05:52Z</updated>
    </source>
  </entry>

  <entry>
    <id>http://code.technically.us/post/998251172</id>
    <link href="http://code.technically.us/post/998251172" rel="alternate" type="text/html"/>
    <title>Holding the Parameter</title>
    <summary type="xhtml"><div xmlns="http://www.w3.org/1999/xhtml"><p>HTTP requests: you want to serve them. You want to respond in the 200s. But some requests just don’t make the cut. They lack the attributes you’re looking for, or they have the attributes but in the wrong proportion. In short, some requests are just a bad <em>match</em>.</p>

<p>The <a href="http://github.com/n8han/unfiltered#readme">Unfiltered</a> web toolkit gives you two ways to handle request parameters. (Those two are in addition to the infinitely many ways you could handle the parameter map yourself, or even directly access the <code>HttpServletRequest</code> if you want to <em>go there</em>.) The first was really easy to build. It’s a natural extension of the pattern matching that Unfiltered uses generally:</p>

<pre><code>object Number extends Params.Extract(
  "number", 
  Params.first ~&gt; Params.int
)
class MyFilter extends unfiltered.Planify({
  case POST(Path("/hi", Params(Number(num, _), _))) =&gt; 
    ResponseString(num.toString)
})
</code></pre>

<p>And that would give you a filter that only responds when a parameter is supplied that’s called “number” and is an integer. It’s a little odd that the extractor must be defined in an object outside the partial function that defines request handling, but the <em>real</em> shortcoming of this approach is that you can’t easily define behavior for when the parameter is missing, or bad. You can nest pattern matching statements to catch some of the failure conditions, but it’s not going to be pretty (or complete).</p>

<p>For an internal service, or a prototype of an external one, descriptively responding to bad inputs may not be a concern. In that case, go to town with the parameter extractor object. It’s an easy and typesafe way to define and handle acceptable inputs. It offloads the effort of dealing with errorneous input to the client making the request.</p>

<p>But most services can’t just tell bad clients to bug off. For them, there’s <code>QParam</code>. It can map parameter failures to very specific error responses, no matter how many parameters fail.</p>

<p>For example!</p>

&lt;iframe frameborder="0" height="200" src="http://sourced.implicit.ly/net.databinder/unfiltered.test/0.1.4/ParamsSpec.scala.html?id=19982" width="570"&gt;<em>If you’re not seeing sexy code here you need to click through to <a href="http://tumblr.com/xsggibzj8">the actual post</a>.</em>
&lt;/iframe&gt;

<p>This rather dense chunk of code will match on any GET request to “/even”, and respond with either a 200 or 400 depending on the validity of the parameters supplied. Its parameter requirements are defined in a <code>for</code> expression, whose <code>yield</code> statement is only evaluated if no errors have accumulated. After defining the requirements, you apply a set of parameters and provide a function to handle the error list if it is non-empty.</p>

<p>In this case we start with a parameter “number” which must parse into an <code>int</code> or the error object “nonnumber” will be recorded. (The type of error objects for an expression is inferred from the first error object supplied.) Secondly, it must satisfy the predicate <code>{ (_: Int) % 2 == 0 }</code> or we’ll note that it was “odd”, and finally it must exist or else it is “missing”. If any requirement on a parameter fails, its remaining requirements are skipped and the next parameter is evaluated.</p>

<p>How does it work? It’s a variation of the state-transformer monad, apparently. I knew how I wanted parameter evaluation to work, and tried to write it “from scratch” but that didn’t produce anything useful. So I ripped off some code from <a href="http://github.com/szeiger/scala-query">ScalaQuery</a> (yes—the SQL API) and that somehow did work. I thought my hack job was pretty slick and showed it to Chris League, who <a href="http://vimeo.com/13304075">spoke to our Meetup group</a> about these fancy topics recently. He promptly rewrote it. After some further negotiation, this is what we ended up with:</p>

&lt;iframe frameborder="0" height="460" src="http://sourced.implicit.ly/net.databinder/unfiltered/0.1.4/request/params.scala.html?id=6843" width="570"&gt;<em><a href="http://tumblr.com/xsggibzj8">Ditto</a>.</em>&lt;/iframe&gt;

<p>And so on.</p>

<p>In case you want to try this stuff out, we added some fun parameter gymnastics to Unfiltered’s <a href="http://github.com/softprops/unfiltered.g8">template project</a>. It’s a <a href="http://github.com/n8han/giter8#readme">giter8</a> template, so if you have <code>g8</code> on your path you can</p>

<pre><code>$ g8 softprops/unfiltered
</code></pre>

<p>and be on your way. Of course, no one has <code>g8</code> on their path yet, so <em>you</em> could be the first person in your timezone to make the <a href="http://github.com/n8han/giter8#readme">exciting leap to the future of Scala applications installed and launched by sbt</a>.</p>

<p>It’s been a busy summer.</p></div>
    </summary>
    <updated>2010-08-23T14:35:00Z</updated>
    <category term="FP"/>
    <category term="Giter8"/>
    <category term="Scala"/>
    <category term="The Static Typing"/>
    <category term="Unfiltered"/>
    <category term="Web"/>
    <category term="La Monade"/>
    <source>
      <id>http://code.technically.us/</id>
      <author>
        <name>Coderspiel</name>
      </author>
      <link href="http://tumblr.superfeedr.com/" rel="hub" type="text/html"/>
      <link href="http://code.technically.us/" rel="alternate" type="text/html"/>
      <link href="http://code.technically.us/rss" rel="self" type="application/rss+xml"/>
      <title>Coderspiel</title>
      <updated>2010-09-09T03:00:39Z</updated>
    </source>
  </entry>

  <entry xml:lang="en">
    <id>http://blog.tmorris.net/?p=801</id>
    <link href="http://blog.tmorris.net/further-understanding-scalaoption/" rel="alternate" type="text/html"/>
    <title>Further understanding scala.Option</title>
    <summary>Below are 15 (probably fun) exercises for anyone interested in obtaining a deeper understanding of scala.Option and algebraic data types in general. I could write the same in Haskell but this will require either type-classes or rank-n types (GHC extension), so I thought I’d give that a miss.
Instructions are in the comments. Let me know [...]</summary>
    <content type="xhtml"><div xmlns="http://www.w3.org/1999/xhtml"><p>Below are 15 (probably fun) exercises for anyone interested in obtaining a deeper understanding of <code>scala.Option</code> and algebraic data types in general. I could write the same in Haskell but this will require either type-classes or rank-n types (GHC extension), so I thought I’d give that a miss.</p>
<p>Instructions are in the comments. Let me know if there are any questions.</p>

<div class="wp_syntax"><div class="code"><pre class="scala"><span style="color: #008000; font-style: italic;">// Scala version 2.8.0.final</span>
<span style="color: #008000; font-style: italic;">// http://scalacheck.googlecode.com/files/scalacheck_2.8.0-1.8-SNAPSHOT.jar</span>
 
 
<span style="color: #00ff00; font-style: italic;">/*
 
  Below are 15 exercises. The task is to emulate the scala.Option API
  without using Some/None subtypes, but instead using a fold (called a
  catamorphism).
 
  A couple of functions are already done (map, get)
  to be used as an example. ScalaCheck tests are given below to
  verify the work. The desired result is to have all tests passing.
 
  The 15th exercise is not available in the existing Scala API so
  instructions are given in the comments.
 
  Revision History
  ================
 
  23/08/2010
  Initial revision
 
  ----------------
 
  23/08/2010
  Fixed prop_getOrElse. Thanks Michael Bayne.
 
  ----------------
 
  26/08/2010
  Add lazy annotation to orElse method.
 
*/</span>
 
 
<span style="color: #0000ff; font-weight: bold;">trait</span> Optional<span style="color: #F78811;">[</span>A<span style="color: #F78811;">]</span> <span style="color: #F78811;">{</span>
  <span style="color: #008000; font-style: italic;">// single abstract method</span>
  <span style="color: #0000ff; font-weight: bold;">def</span> fold<span style="color: #F78811;">[</span>X<span style="color: #F78811;">]</span><span style="color: #F78811;">(</span>some<span style="color: #000080;">:</span> A <span style="color: #000080;">=&gt;</span> X, none<span style="color: #000080;">:</span> <span style="color: #000080;">=&gt;</span> X<span style="color: #F78811;">)</span><span style="color: #000080;">:</span> X
 
  <span style="color: #0000ff; font-weight: bold;">import</span> Optional.<span style="color: #000080;">_</span>
 
  <span style="color: #008000; font-style: italic;">// Done for you.</span>
  <span style="color: #0000ff; font-weight: bold;">def</span> map<span style="color: #F78811;">[</span>B<span style="color: #F78811;">]</span><span style="color: #F78811;">(</span>f<span style="color: #000080;">:</span> A <span style="color: #000080;">=&gt;</span> B<span style="color: #F78811;">)</span><span style="color: #000080;">:</span> Optional<span style="color: #F78811;">[</span>B<span style="color: #F78811;">]</span> <span style="color: #000080;">=</span>
    fold<span style="color: #F78811;">(</span>f andThen some, none<span style="color: #F78811;">[</span>B<span style="color: #F78811;">]</span><span style="color: #F78811;">)</span>
 
  <span style="color: #008000; font-style: italic;">// Done for you.</span>
  <span style="color: #008000; font-style: italic;">// WARNING: undefined for None</span>
  <span style="color: #0000ff; font-weight: bold;">def</span> get<span style="color: #000080;">:</span> A <span style="color: #000080;">=</span>
    fold<span style="color: #F78811;">(</span>a <span style="color: #000080;">=&gt;</span> a, error<span style="color: #F78811;">(</span><span style="color: #6666FF;">"None.get"</span><span style="color: #F78811;">)</span><span style="color: #F78811;">)</span>
 
  <span style="color: #008000; font-style: italic;">// Exercise 1</span>
  <span style="color: #0000ff; font-weight: bold;">def</span> flatMap<span style="color: #F78811;">[</span>B<span style="color: #F78811;">]</span><span style="color: #F78811;">(</span>f<span style="color: #000080;">:</span> A <span style="color: #000080;">=&gt;</span> Optional<span style="color: #F78811;">[</span>B<span style="color: #F78811;">]</span><span style="color: #F78811;">)</span><span style="color: #000080;">:</span> Optional<span style="color: #F78811;">[</span>B<span style="color: #F78811;">]</span> <span style="color: #000080;">=</span>
    error<span style="color: #F78811;">(</span><span style="color: #6666FF;">"todo"</span><span style="color: #F78811;">)</span>
 
  <span style="color: #008000; font-style: italic;">// Exercise 2</span>
  <span style="color: #008000; font-style: italic;">// Rewrite map but use flatMap, not fold.</span>
  <span style="color: #0000ff; font-weight: bold;">def</span> mapAgain<span style="color: #F78811;">[</span>B<span style="color: #F78811;">]</span><span style="color: #F78811;">(</span>f<span style="color: #000080;">:</span> A <span style="color: #000080;">=&gt;</span> B<span style="color: #F78811;">)</span><span style="color: #000080;">:</span> Optional<span style="color: #F78811;">[</span>B<span style="color: #F78811;">]</span> <span style="color: #000080;">=</span>
    error<span style="color: #F78811;">(</span><span style="color: #6666FF;">"todo"</span><span style="color: #F78811;">)</span>
 
  <span style="color: #008000; font-style: italic;">// Exercise 3</span>
  <span style="color: #0000ff; font-weight: bold;">def</span> getOrElse<span style="color: #F78811;">(</span>e<span style="color: #000080;">:</span> <span style="color: #000080;">=&gt;</span> A<span style="color: #F78811;">)</span><span style="color: #000080;">:</span> A <span style="color: #000080;">=</span>
    error<span style="color: #F78811;">(</span><span style="color: #6666FF;">"todo"</span><span style="color: #F78811;">)</span>
 
  <span style="color: #008000; font-style: italic;">// Exercise 4</span>
  <span style="color: #0000ff; font-weight: bold;">def</span> filter<span style="color: #F78811;">(</span>p<span style="color: #000080;">:</span> A <span style="color: #000080;">=&gt;</span> <span style="color: #9999cc; font-weight: bold;">Boolean</span><span style="color: #F78811;">)</span><span style="color: #000080;">:</span> Optional<span style="color: #F78811;">[</span>A<span style="color: #F78811;">]</span> <span style="color: #000080;">=</span>
    error<span style="color: #F78811;">(</span><span style="color: #6666FF;">"todo"</span><span style="color: #F78811;">)</span>
 
  <span style="color: #008000; font-style: italic;">// Exercise 5</span>
  <span style="color: #0000ff; font-weight: bold;">def</span> exists<span style="color: #F78811;">(</span>p<span style="color: #000080;">:</span> A <span style="color: #000080;">=&gt;</span> <span style="color: #9999cc; font-weight: bold;">Boolean</span><span style="color: #F78811;">)</span><span style="color: #000080;">:</span> <span style="color: #9999cc; font-weight: bold;">Boolean</span> <span style="color: #000080;">=</span>
    error<span style="color: #F78811;">(</span><span style="color: #6666FF;">"todo"</span><span style="color: #F78811;">)</span>
 
  <span style="color: #008000; font-style: italic;">// Exercise 6</span>
  <span style="color: #0000ff; font-weight: bold;">def</span> forall<span style="color: #F78811;">(</span>p<span style="color: #000080;">:</span> A <span style="color: #000080;">=&gt;</span> <span style="color: #9999cc; font-weight: bold;">Boolean</span><span style="color: #F78811;">)</span><span style="color: #000080;">:</span> <span style="color: #9999cc; font-weight: bold;">Boolean</span> <span style="color: #000080;">=</span>
    error<span style="color: #F78811;">(</span><span style="color: #6666FF;">"todo"</span><span style="color: #F78811;">)</span>
 
  <span style="color: #008000; font-style: italic;">// Exercise 7</span>
  <span style="color: #0000ff; font-weight: bold;">def</span> foreach<span style="color: #F78811;">(</span>f<span style="color: #000080;">:</span> A <span style="color: #000080;">=&gt;</span> Unit<span style="color: #F78811;">)</span><span style="color: #000080;">:</span> Unit <span style="color: #000080;">=</span>
    error<span style="color: #F78811;">(</span><span style="color: #6666FF;">"todo"</span><span style="color: #F78811;">)</span>
 
  <span style="color: #008000; font-style: italic;">// Exercise 8</span>
  <span style="color: #0000ff; font-weight: bold;">def</span> isDefined<span style="color: #000080;">:</span> <span style="color: #9999cc; font-weight: bold;">Boolean</span> <span style="color: #000080;">=</span>
    error<span style="color: #F78811;">(</span><span style="color: #6666FF;">"todo"</span><span style="color: #F78811;">)</span>
 
  <span style="color: #008000; font-style: italic;">// Exercise 9</span>
  <span style="color: #0000ff; font-weight: bold;">def</span> isEmpty<span style="color: #000080;">:</span> <span style="color: #9999cc; font-weight: bold;">Boolean</span> <span style="color: #000080;">=</span>
    error<span style="color: #F78811;">(</span><span style="color: #6666FF;">"todo"</span><span style="color: #F78811;">)</span>
 
  <span style="color: #008000; font-style: italic;">// Exercise 10</span>
  <span style="color: #0000ff; font-weight: bold;">def</span> orElse<span style="color: #F78811;">(</span>o<span style="color: #000080;">:</span> <span style="color: #000080;">=&gt;</span> Optional<span style="color: #F78811;">[</span>A<span style="color: #F78811;">]</span><span style="color: #F78811;">)</span><span style="color: #000080;">:</span> Optional<span style="color: #F78811;">[</span>A<span style="color: #F78811;">]</span> <span style="color: #000080;">=</span>
    error<span style="color: #F78811;">(</span><span style="color: #6666FF;">"todo"</span><span style="color: #F78811;">)</span>
 
  <span style="color: #008000; font-style: italic;">// Exercise 11</span>
  <span style="color: #0000ff; font-weight: bold;">def</span> toLeft<span style="color: #F78811;">[</span>X<span style="color: #F78811;">]</span><span style="color: #F78811;">(</span>right<span style="color: #000080;">:</span> <span style="color: #000080;">=&gt;</span> X<span style="color: #F78811;">)</span><span style="color: #000080;">:</span> Either<span style="color: #F78811;">[</span>A, X<span style="color: #F78811;">]</span> <span style="color: #000080;">=</span>
    error<span style="color: #F78811;">(</span><span style="color: #6666FF;">"todo"</span><span style="color: #F78811;">)</span>
 
  <span style="color: #008000; font-style: italic;">// Exercise 12</span>
  <span style="color: #0000ff; font-weight: bold;">def</span> toRight<span style="color: #F78811;">[</span>X<span style="color: #F78811;">]</span><span style="color: #F78811;">(</span>left<span style="color: #000080;">:</span> <span style="color: #000080;">=&gt;</span> X<span style="color: #F78811;">)</span><span style="color: #000080;">:</span> Either<span style="color: #F78811;">[</span>X, A<span style="color: #F78811;">]</span> <span style="color: #000080;">=</span>
    error<span style="color: #F78811;">(</span><span style="color: #6666FF;">"todo"</span><span style="color: #F78811;">)</span>
 
  <span style="color: #008000; font-style: italic;">// Exercise 13</span>
  <span style="color: #0000ff; font-weight: bold;">def</span> toList<span style="color: #000080;">:</span> List<span style="color: #F78811;">[</span>A<span style="color: #F78811;">]</span> <span style="color: #000080;">=</span>
    error<span style="color: #F78811;">(</span><span style="color: #6666FF;">"todo"</span><span style="color: #F78811;">)</span>
 
  <span style="color: #008000; font-style: italic;">// Exercise 14</span>
  <span style="color: #0000ff; font-weight: bold;">def</span> iterator<span style="color: #000080;">:</span> Iterator<span style="color: #F78811;">[</span>A<span style="color: #F78811;">]</span> <span style="color: #000080;">=</span>
    error<span style="color: #F78811;">(</span><span style="color: #6666FF;">"todo"</span><span style="color: #F78811;">)</span>
 
  <span style="color: #008000; font-style: italic;">// Exercise 15 The Clincher!</span>
  <span style="color: #008000; font-style: italic;">// Return a none value if either this or the argument is none.</span>
  <span style="color: #008000; font-style: italic;">// Otherwise apply the function to the argument in some.</span>
  <span style="color: #008000; font-style: italic;">// Don't be afraid to use functions you have written.</span>
  <span style="color: #008000; font-style: italic;">// Better style, more points!</span>
  <span style="color: #0000ff; font-weight: bold;">def</span> applic<span style="color: #F78811;">[</span>B<span style="color: #F78811;">]</span><span style="color: #F78811;">(</span>f<span style="color: #000080;">:</span> Optional<span style="color: #F78811;">[</span>A <span style="color: #000080;">=&gt;</span> B<span style="color: #F78811;">]</span><span style="color: #F78811;">)</span><span style="color: #000080;">:</span> Optional<span style="color: #F78811;">[</span>B<span style="color: #F78811;">]</span> <span style="color: #000080;">=</span>
    error<span style="color: #F78811;">(</span><span style="color: #6666FF;">"todo"</span><span style="color: #F78811;">)</span>
 
  <span style="color: #008000; font-style: italic;">// Utility</span>
  <span style="color: #0000ff; font-weight: bold;">def</span> toOption<span style="color: #000080;">:</span> Option<span style="color: #F78811;">[</span>A<span style="color: #F78811;">]</span> <span style="color: #000080;">=</span> fold<span style="color: #F78811;">(</span>Some<span style="color: #F78811;">(</span><span style="color: #000080;">_</span><span style="color: #F78811;">)</span>, None<span style="color: #F78811;">)</span>
<span style="color: #F78811;">}</span>
 
<span style="color: #0000ff; font-weight: bold;">object</span> Optional <span style="color: #F78811;">{</span>
  <span style="color: #008000; font-style: italic;">// Done for you</span>
  <span style="color: #0000ff; font-weight: bold;">def</span> none<span style="color: #F78811;">[</span>A<span style="color: #F78811;">]</span><span style="color: #000080;">:</span> Optional<span style="color: #F78811;">[</span>A<span style="color: #F78811;">]</span> <span style="color: #000080;">=</span> <span style="color: #0000ff; font-weight: bold;">new</span> Optional<span style="color: #F78811;">[</span>A<span style="color: #F78811;">]</span> <span style="color: #F78811;">{</span>
    <span style="color: #0000ff; font-weight: bold;">def</span> fold<span style="color: #F78811;">[</span>X<span style="color: #F78811;">]</span><span style="color: #F78811;">(</span>some<span style="color: #000080;">:</span> A <span style="color: #000080;">=&gt;</span> X, none<span style="color: #000080;">:</span> <span style="color: #000080;">=&gt;</span> X<span style="color: #F78811;">)</span> <span style="color: #000080;">=</span> none
  <span style="color: #F78811;">}</span>
 
  <span style="color: #008000; font-style: italic;">// Done for you</span>
  <span style="color: #0000ff; font-weight: bold;">def</span> some<span style="color: #F78811;">[</span>A<span style="color: #F78811;">]</span><span style="color: #F78811;">(</span>a<span style="color: #000080;">:</span> A<span style="color: #F78811;">)</span><span style="color: #000080;">:</span> Optional<span style="color: #F78811;">[</span>A<span style="color: #F78811;">]</span> <span style="color: #000080;">=</span> <span style="color: #0000ff; font-weight: bold;">new</span> Optional<span style="color: #F78811;">[</span>A<span style="color: #F78811;">]</span> <span style="color: #F78811;">{</span>
    <span style="color: #0000ff; font-weight: bold;">def</span> fold<span style="color: #F78811;">[</span>X<span style="color: #F78811;">]</span><span style="color: #F78811;">(</span>some<span style="color: #000080;">:</span> A <span style="color: #000080;">=&gt;</span> X, none<span style="color: #000080;">:</span> <span style="color: #000080;">=&gt;</span> X<span style="color: #F78811;">)</span> <span style="color: #000080;">=</span> some<span style="color: #F78811;">(</span>a<span style="color: #F78811;">)</span>
  <span style="color: #F78811;">}</span>
 
  <span style="color: #008000; font-style: italic;">// Utility</span>
  <span style="color: #0000ff; font-weight: bold;">def</span> fromOption<span style="color: #F78811;">[</span>A<span style="color: #F78811;">]</span><span style="color: #F78811;">(</span>o<span style="color: #000080;">:</span> Option<span style="color: #F78811;">[</span>A<span style="color: #F78811;">]</span><span style="color: #F78811;">)</span><span style="color: #000080;">:</span> Optional<span style="color: #F78811;">[</span>A<span style="color: #F78811;">]</span> <span style="color: #000080;">=</span> o <span style="color: #0000ff; font-weight: bold;">match</span> <span style="color: #F78811;">{</span>
    <span style="color: #0000ff; font-weight: bold;">case</span> None    <span style="color: #000080;">=&gt;</span> none
    <span style="color: #0000ff; font-weight: bold;">case</span> Some<span style="color: #F78811;">(</span>a<span style="color: #F78811;">)</span> <span style="color: #000080;">=&gt;</span> some<span style="color: #F78811;">(</span>a<span style="color: #F78811;">)</span>
  <span style="color: #F78811;">}</span>
<span style="color: #F78811;">}</span>
 
<span style="color: #0000ff; font-weight: bold;">import</span> org.<span style="color: #000000;">scalacheck</span>.<span style="color: #000080;">_</span>
<span style="color: #0000ff; font-weight: bold;">import</span> Arbitrary.<span style="color: #000000;">arbitrary</span>
<span style="color: #0000ff; font-weight: bold;">import</span> Prop.<span style="color: #000080;">_</span>
 
<span style="color: #0000ff; font-weight: bold;">object</span> TestOptional <span style="color: #F78811;">{</span>
  <span style="color: #0000ff; font-weight: bold;">import</span> Optional.<span style="color: #000080;">_</span>
 
  <span style="color: #0000ff; font-weight: bold;">implicit</span> <span style="color: #0000ff; font-weight: bold;">def</span> ArbitraryOptional<span style="color: #F78811;">[</span>A<span style="color: #F78811;">]</span><span style="color: #F78811;">(</span><span style="color: #0000ff; font-weight: bold;">implicit</span> a<span style="color: #000080;">:</span> Arbitrary<span style="color: #F78811;">[</span>A<span style="color: #F78811;">]</span><span style="color: #F78811;">)</span><span style="color: #000080;">:</span> Arbitrary<span style="color: #F78811;">[</span>Optional<span style="color: #F78811;">[</span>A<span style="color: #F78811;">]</span><span style="color: #F78811;">]</span> <span style="color: #000080;">=</span>
    Arbitrary<span style="color: #F78811;">(</span>arbitrary<span style="color: #F78811;">[</span>Option<span style="color: #F78811;">[</span>A<span style="color: #F78811;">]</span><span style="color: #F78811;">]</span> map fromOption<span style="color: #F78811;">)</span>
 
  <span style="color: #0000ff; font-weight: bold;">val</span> prop<span style="color: #000080;">_</span>map <span style="color: #000080;">=</span> forAll <span style="color: #F78811;">(</span><span style="color: #F78811;">(</span>o<span style="color: #000080;">:</span> Optional<span style="color: #F78811;">[</span><span style="color: #9999cc; font-weight: bold;">Int</span><span style="color: #F78811;">]</span>, f<span style="color: #000080;">:</span> <span style="color: #9999cc; font-weight: bold;">Int</span> <span style="color: #000080;">=&gt;</span> String<span style="color: #F78811;">)</span> <span style="color: #000080;">=&gt;</span>
    <span style="color: #F78811;">(</span>o map f<span style="color: #F78811;">)</span>.<span style="color: #000000;">toOption</span> <span style="color: #000080;">==</span> <span style="color: #F78811;">(</span>o.<span style="color: #000000;">toOption</span> map f<span style="color: #F78811;">)</span><span style="color: #F78811;">)</span>
 
  <span style="color: #0000ff; font-weight: bold;">val</span> prop<span style="color: #000080;">_</span>get <span style="color: #000080;">=</span> forAll<span style="color: #F78811;">(</span><span style="color: #F78811;">(</span>o<span style="color: #000080;">:</span> Optional<span style="color: #F78811;">[</span><span style="color: #9999cc; font-weight: bold;">Int</span><span style="color: #F78811;">]</span><span style="color: #F78811;">)</span> <span style="color: #000080;">=&gt;</span>
    o.<span style="color: #000000;">isDefined</span> <span style="color: #000080;">==&gt;</span>
      <span style="color: #F78811;">(</span>o.<span style="color: #000000;">get</span> <span style="color: #000080;">==</span> o.<span style="color: #000000;">toOption</span>.<span style="color: #000000;">get</span><span style="color: #F78811;">)</span><span style="color: #F78811;">)</span>
 
  <span style="color: #0000ff; font-weight: bold;">val</span> prop<span style="color: #000080;">_</span>flatMap <span style="color: #000080;">=</span> forAll<span style="color: #F78811;">(</span><span style="color: #F78811;">(</span>o<span style="color: #000080;">:</span> Optional<span style="color: #F78811;">[</span><span style="color: #9999cc; font-weight: bold;">Int</span><span style="color: #F78811;">]</span>, f<span style="color: #000080;">:</span> <span style="color: #9999cc; font-weight: bold;">Int</span> <span style="color: #000080;">=&gt;</span> Optional<span style="color: #F78811;">[</span>String<span style="color: #F78811;">]</span><span style="color: #F78811;">)</span> <span style="color: #000080;">=&gt;</span>
    <span style="color: #F78811;">(</span>o flatMap f<span style="color: #F78811;">)</span>.<span style="color: #000000;">toOption</span> <span style="color: #000080;">==</span> <span style="color: #F78811;">(</span>o.<span style="color: #000000;">toOption</span> flatMap <span style="color: #F78811;">(</span>f<span style="color: #F78811;">(</span><span style="color: #000080;">_</span><span style="color: #F78811;">)</span>.<span style="color: #000000;">toOption</span><span style="color: #F78811;">)</span><span style="color: #F78811;">)</span><span style="color: #F78811;">)</span>
 
  <span style="color: #0000ff; font-weight: bold;">val</span> prop<span style="color: #000080;">_</span>mapAgain <span style="color: #000080;">=</span> forAll <span style="color: #F78811;">(</span><span style="color: #F78811;">(</span>o<span style="color: #000080;">:</span> Optional<span style="color: #F78811;">[</span><span style="color: #9999cc; font-weight: bold;">Int</span><span style="color: #F78811;">]</span>, f<span style="color: #000080;">:</span> <span style="color: #9999cc; font-weight: bold;">Int</span> <span style="color: #000080;">=&gt;</span> String<span style="color: #F78811;">)</span> <span style="color: #000080;">=&gt;</span>
    <span style="color: #F78811;">(</span>o mapAgain f<span style="color: #F78811;">)</span>.<span style="color: #000000;">toOption</span> <span style="color: #000080;">==</span> <span style="color: #F78811;">(</span>o map f<span style="color: #F78811;">)</span>.<span style="color: #000000;">toOption</span><span style="color: #F78811;">)</span>
 
  <span style="color: #0000ff; font-weight: bold;">val</span> prop<span style="color: #000080;">_</span>getOrElse <span style="color: #000080;">=</span> forAll <span style="color: #F78811;">(</span><span style="color: #F78811;">(</span>o<span style="color: #000080;">:</span> Optional<span style="color: #F78811;">[</span><span style="color: #9999cc; font-weight: bold;">Int</span><span style="color: #F78811;">]</span>, n<span style="color: #000080;">:</span> <span style="color: #9999cc; font-weight: bold;">Int</span><span style="color: #F78811;">)</span> <span style="color: #000080;">=&gt;</span>
    <span style="color: #F78811;">(</span>o getOrElse n<span style="color: #F78811;">)</span> <span style="color: #000080;">==</span> <span style="color: #F78811;">(</span>o.<span style="color: #000000;">toOption</span> getOrElse n<span style="color: #F78811;">)</span><span style="color: #F78811;">)</span>
 
  <span style="color: #0000ff; font-weight: bold;">val</span> prop<span style="color: #000080;">_</span>filter <span style="color: #000080;">=</span> forAll <span style="color: #F78811;">(</span><span style="color: #F78811;">(</span>o<span style="color: #000080;">:</span> Optional<span style="color: #F78811;">[</span><span style="color: #9999cc; font-weight: bold;">Int</span><span style="color: #F78811;">]</span>, f<span style="color: #000080;">:</span> <span style="color: #9999cc; font-weight: bold;">Int</span> <span style="color: #000080;">=&gt;</span> <span style="color: #9999cc; font-weight: bold;">Boolean</span><span style="color: #F78811;">)</span> <span style="color: #000080;">=&gt;</span>
    <span style="color: #F78811;">(</span>o filter f<span style="color: #F78811;">)</span>.<span style="color: #000000;">toOption</span> <span style="color: #000080;">==</span> <span style="color: #F78811;">(</span>o.<span style="color: #000000;">toOption</span> filter f<span style="color: #F78811;">)</span><span style="color: #F78811;">)</span>
 
  <span style="color: #0000ff; font-weight: bold;">val</span> prop<span style="color: #000080;">_</span>exists <span style="color: #000080;">=</span> forAll <span style="color: #F78811;">(</span><span style="color: #F78811;">(</span>o<span style="color: #000080;">:</span> Optional<span style="color: #F78811;">[</span><span style="color: #9999cc; font-weight: bold;">Int</span><span style="color: #F78811;">]</span>, f<span style="color: #000080;">:</span> <span style="color: #9999cc; font-weight: bold;">Int</span> <span style="color: #000080;">=&gt;</span> <span style="color: #9999cc; font-weight: bold;">Boolean</span><span style="color: #F78811;">)</span> <span style="color: #000080;">=&gt;</span>
    <span style="color: #F78811;">(</span>o exists f<span style="color: #F78811;">)</span> <span style="color: #000080;">==</span> <span style="color: #F78811;">(</span>o.<span style="color: #000000;">toOption</span> exists f<span style="color: #F78811;">)</span><span style="color: #F78811;">)</span>
 
  <span style="color: #0000ff; font-weight: bold;">val</span> prop<span style="color: #000080;">_</span>forall <span style="color: #000080;">=</span> forAll <span style="color: #F78811;">(</span><span style="color: #F78811;">(</span>o<span style="color: #000080;">:</span> Optional<span style="color: #F78811;">[</span><span style="color: #9999cc; font-weight: bold;">Int</span><span style="color: #F78811;">]</span>, f<span style="color: #000080;">:</span> <span style="color: #9999cc; font-weight: bold;">Int</span> <span style="color: #000080;">=&gt;</span> <span style="color: #9999cc; font-weight: bold;">Boolean</span><span style="color: #F78811;">)</span> <span style="color: #000080;">=&gt;</span>
    <span style="color: #F78811;">(</span>o forall f<span style="color: #F78811;">)</span> <span style="color: #000080;">==</span> <span style="color: #F78811;">(</span>o.<span style="color: #000000;">toOption</span> forall f<span style="color: #F78811;">)</span><span style="color: #F78811;">)</span>
 
  <span style="color: #0000ff; font-weight: bold;">val</span> prop<span style="color: #000080;">_</span>foreach <span style="color: #000080;">=</span> forAll <span style="color: #F78811;">(</span><span style="color: #F78811;">(</span>o<span style="color: #000080;">:</span> Optional<span style="color: #F78811;">[</span><span style="color: #9999cc; font-weight: bold;">Int</span><span style="color: #F78811;">]</span>, f<span style="color: #000080;">:</span> <span style="color: #9999cc; font-weight: bold;">Int</span> <span style="color: #000080;">=&gt;</span> Unit, n<span style="color: #000080;">:</span> <span style="color: #9999cc; font-weight: bold;">Int</span><span style="color: #F78811;">)</span> <span style="color: #000080;">=&gt;</span> <span style="color: #F78811;">{</span>
    <span style="color: #0000ff; font-weight: bold;">var</span> x<span style="color: #000080;">:</span> <span style="color: #9999cc; font-weight: bold;">Int</span> <span style="color: #000080;">=</span> n
    <span style="color: #0000ff; font-weight: bold;">var</span> y<span style="color: #000080;">:</span> <span style="color: #9999cc; font-weight: bold;">Int</span> <span style="color: #000080;">=</span> x
 
    o foreach <span style="color: #F78811;">(</span>t <span style="color: #000080;">=&gt;</span> x <span style="color: #000080;">=</span> x + t<span style="color: #F78811;">)</span>
    o.<span style="color: #000000;">toOption</span> foreach <span style="color: #F78811;">(</span>t <span style="color: #000080;">=&gt;</span> y <span style="color: #000080;">=</span> y + t<span style="color: #F78811;">)</span>
 
    x <span style="color: #000080;">==</span> y
  <span style="color: #F78811;">}</span><span style="color: #F78811;">)</span>
 
  <span style="color: #0000ff; font-weight: bold;">val</span> prop<span style="color: #000080;">_</span>isDefined <span style="color: #000080;">=</span> forAll <span style="color: #F78811;">(</span><span style="color: #F78811;">(</span>o<span style="color: #000080;">:</span> Optional<span style="color: #F78811;">[</span><span style="color: #9999cc; font-weight: bold;">Int</span><span style="color: #F78811;">]</span><span style="color: #F78811;">)</span> <span style="color: #000080;">=&gt;</span>
    <span style="color: #F78811;">(</span>o.<span style="color: #000000;">isDefined</span><span style="color: #F78811;">)</span> <span style="color: #000080;">==</span> <span style="color: #F78811;">(</span>o.<span style="color: #000000;">toOption</span>.<span style="color: #000000;">isDefined</span><span style="color: #F78811;">)</span><span style="color: #F78811;">)</span>
 
  <span style="color: #0000ff; font-weight: bold;">val</span> prop<span style="color: #000080;">_</span>isEmpty <span style="color: #000080;">=</span> forAll <span style="color: #F78811;">(</span><span style="color: #F78811;">(</span>o<span style="color: #000080;">:</span> Optional<span style="color: #F78811;">[</span><span style="color: #9999cc; font-weight: bold;">Int</span><span style="color: #F78811;">]</span><span style="color: #F78811;">)</span> <span style="color: #000080;">=&gt;</span>
    o.<span style="color: #000000;">isEmpty</span> <span style="color: #000080;">==</span> o.<span style="color: #000000;">toOption</span>.<span style="color: #000000;">isEmpty</span><span style="color: #F78811;">)</span>
 
  <span style="color: #0000ff; font-weight: bold;">val</span> prop<span style="color: #000080;">_</span>orElse <span style="color: #000080;">=</span> forAll <span style="color: #F78811;">(</span><span style="color: #F78811;">(</span>o<span style="color: #000080;">:</span> Optional<span style="color: #F78811;">[</span><span style="color: #9999cc; font-weight: bold;">Int</span><span style="color: #F78811;">]</span>, p<span style="color: #000080;">:</span> Optional<span style="color: #F78811;">[</span><span style="color: #9999cc; font-weight: bold;">Int</span><span style="color: #F78811;">]</span><span style="color: #F78811;">)</span> <span style="color: #000080;">=&gt;</span>
    <span style="color: #F78811;">(</span>o orElse p<span style="color: #F78811;">)</span>.<span style="color: #000000;">toOption</span> <span style="color: #000080;">==</span> <span style="color: #F78811;">(</span>o.<span style="color: #000000;">toOption</span> orElse p.<span style="color: #000000;">toOption</span><span style="color: #F78811;">)</span><span style="color: #F78811;">)</span>
 
  <span style="color: #0000ff; font-weight: bold;">val</span> prop<span style="color: #000080;">_</span>toLeft <span style="color: #000080;">=</span> forAll <span style="color: #F78811;">(</span><span style="color: #F78811;">(</span>o<span style="color: #000080;">:</span> Optional<span style="color: #F78811;">[</span><span style="color: #9999cc; font-weight: bold;">Int</span><span style="color: #F78811;">]</span>, n<span style="color: #000080;">:</span> <span style="color: #9999cc; font-weight: bold;">Int</span><span style="color: #F78811;">)</span> <span style="color: #000080;">=&gt;</span>
    <span style="color: #F78811;">(</span>o toLeft n<span style="color: #F78811;">)</span> <span style="color: #000080;">==</span> <span style="color: #F78811;">(</span>o.<span style="color: #000000;">toOption</span> toLeft n<span style="color: #F78811;">)</span><span style="color: #F78811;">)</span>
 
  <span style="color: #0000ff; font-weight: bold;">val</span> prop<span style="color: #000080;">_</span>toRight <span style="color: #000080;">=</span> forAll <span style="color: #F78811;">(</span><span style="color: #F78811;">(</span>o<span style="color: #000080;">:</span> Optional<span style="color: #F78811;">[</span><span style="color: #9999cc; font-weight: bold;">Int</span><span style="color: #F78811;">]</span>, n<span style="color: #000080;">:</span> <span style="color: #9999cc; font-weight: bold;">Int</span><span style="color: #F78811;">)</span> <span style="color: #000080;">=&gt;</span>
    <span style="color: #F78811;">(</span>o toRight n<span style="color: #F78811;">)</span> <span style="color: #000080;">==</span> <span style="color: #F78811;">(</span>o.<span style="color: #000000;">toOption</span> toRight n<span style="color: #F78811;">)</span><span style="color: #F78811;">)</span>
 
  <span style="color: #0000ff; font-weight: bold;">val</span> prop<span style="color: #000080;">_</span>toList <span style="color: #000080;">=</span> forAll <span style="color: #F78811;">(</span><span style="color: #F78811;">(</span>o<span style="color: #000080;">:</span> Optional<span style="color: #F78811;">[</span><span style="color: #9999cc; font-weight: bold;">Int</span><span style="color: #F78811;">]</span><span style="color: #F78811;">)</span> <span style="color: #000080;">=&gt;</span>
    o.<span style="color: #000000;">toList</span> <span style="color: #000080;">==</span> o.<span style="color: #000000;">toOption</span>.<span style="color: #000000;">toList</span><span style="color: #F78811;">)</span>
 
  <span style="color: #0000ff; font-weight: bold;">val</span> prop<span style="color: #000080;">_</span>iterator <span style="color: #000080;">=</span> forAll <span style="color: #F78811;">(</span><span style="color: #F78811;">(</span>o<span style="color: #000080;">:</span> Optional<span style="color: #F78811;">[</span><span style="color: #9999cc; font-weight: bold;">Int</span><span style="color: #F78811;">]</span><span style="color: #F78811;">)</span> <span style="color: #000080;">=&gt;</span>
    o.<span style="color: #000000;">iterator</span> sameElements o.<span style="color: #000000;">toOption</span>.<span style="color: #000000;">iterator</span><span style="color: #F78811;">)</span>
 
  <span style="color: #008000; font-style: italic;">// *** READ THIS COMMENT FIRST ***</span>
  <span style="color: #008000; font-style: italic;">// Note that scala.Option has no such equivalent to this method</span>
  <span style="color: #008000; font-style: italic;">// Therefore, reading this test may give away clues to how it might be solved.</span>
  <span style="color: #008000; font-style: italic;">// If you do not wish to spoil it, look away now and follow the </span>
  <span style="color: #008000; font-style: italic;">// instruction in the Exercise comment.</span>
  <span style="color: #0000ff; font-weight: bold;">val</span> prop<span style="color: #000080;">_</span>applic <span style="color: #000080;">=</span> forAll <span style="color: #F78811;">(</span><span style="color: #F78811;">(</span>o<span style="color: #000080;">:</span> Optional<span style="color: #F78811;">[</span><span style="color: #9999cc; font-weight: bold;">Int</span> <span style="color: #000080;">=&gt;</span> String<span style="color: #F78811;">]</span>, p<span style="color: #000080;">:</span> Optional<span style="color: #F78811;">[</span><span style="color: #9999cc; font-weight: bold;">Int</span><span style="color: #F78811;">]</span><span style="color: #F78811;">)</span> <span style="color: #000080;">=&gt;</span>
    <span style="color: #F78811;">(</span>p applic o<span style="color: #F78811;">)</span>.<span style="color: #000000;">toOption</span> <span style="color: #000080;">==</span>
    <span style="color: #F78811;">(</span><span style="color: #0000ff; font-weight: bold;">for</span><span style="color: #F78811;">(</span>f <span style="color: #000080;">&lt;</span>- o.<span style="color: #000000;">toOption</span><span style="color: #000080;">;</span>
        n <span style="color: #000080;">&lt;</span>- p.<span style="color: #000000;">toOption</span><span style="color: #F78811;">)</span>
    <span style="color: #0000ff; font-weight: bold;">yield</span> f<span style="color: #F78811;">(</span>n<span style="color: #F78811;">)</span><span style="color: #F78811;">)</span><span style="color: #F78811;">)</span>
 
  <span style="color: #0000ff; font-weight: bold;">val</span> props <span style="color: #000080;">=</span>
    List<span style="color: #F78811;">(</span>
      prop<span style="color: #000080;">_</span>map,
      prop<span style="color: #000080;">_</span>get,
      prop<span style="color: #000080;">_</span>flatMap,
      prop<span style="color: #000080;">_</span>mapAgain,
      prop<span style="color: #000080;">_</span>getOrElse,
      prop<span style="color: #000080;">_</span>filter,
      prop<span style="color: #000080;">_</span>exists,
      prop<span style="color: #000080;">_</span>forall,
      prop<span style="color: #000080;">_</span>foreach,
      prop<span style="color: #000080;">_</span>isDefined,
      prop<span style="color: #000080;">_</span>isEmpty,
      prop<span style="color: #000080;">_</span>orElse,
      prop<span style="color: #000080;">_</span>toLeft,
      prop<span style="color: #000080;">_</span>toRight,
      prop<span style="color: #000080;">_</span>toList,
      prop<span style="color: #000080;">_</span>iterator,
      prop<span style="color: #000080;">_</span>applic
    <span style="color: #F78811;">)</span>
 
  <span style="color: #00ff00; font-style: italic;">/*
  $ scala -classpath .:scalacheck_2.8.0-1.8-SNAPSHOT.jar TestOptional
  + OK, passed 100 tests.                                                       
  + OK, passed 100 tests.                                                       
  + OK, passed 100 tests.                                                       
  + OK, passed 100 tests.                                                       
  + OK, passed 100 tests.                                                       
  + OK, passed 100 tests.                                                       
  + OK, passed 100 tests.                                                       
  + OK, passed 100 tests.                                                       
  + OK, passed 100 tests.                                                       
  + OK, passed 100 tests.                                                       
  + OK, passed 100 tests.                                                       
  + OK, passed 100 tests.                                                       
  + OK, passed 100 tests.                                                       
  + OK, passed 100 tests.                                                       
  + OK, passed 100 tests.                                                       
  + OK, passed 100 tests.                                                       
  + OK, passed 100 tests.                       
  */</span>
  <span style="color: #0000ff; font-weight: bold;">def</span> main<span style="color: #F78811;">(</span>args<span style="color: #000080;">:</span> Array<span style="color: #F78811;">[</span>String<span style="color: #F78811;">]</span><span style="color: #F78811;">)</span> <span style="color: #F78811;">{</span>
    props foreach <span style="color: #F78811;">(</span><span style="color: #000080;">_</span>.<span style="color: #000000;">check</span><span style="color: #F78811;">)</span>
  <span style="color: #F78811;">}</span>
<span style="color: #F78811;">}</span></pre></div></div></div>
    </content>
    <updated>2010-08-23T01:46:56Z</updated>
    <category term="Programming"/>
    <author>
      <name>Tony Morris</name>
    </author>
    <source>
      <id>http://blog.tmorris.net</id>
      <link href="http://blog.tmorris.net/category/programming/feed/" rel="self" type="application/atom+xml"/>
      <link href="http://blog.tmorris.net" rel="alternate" type="text/html"/>
      <subtitle>The weblog of Tony Morris</subtitle>
      <title>λ Tony’s blog λ » Programming</title>
      <updated>2010-09-01T23:54:25Z</updated>
    </source>
  </entry>

  <entry>
    <id>tag:blogger.com,1999:blog-19725519.post-3926620988428095194</id>
    <link href="http://erikengbrecht.blogspot.com/2010/08/scala-actors-loop-react-and-schedulers.html" rel="alternate" type="text/html"/>
    <title>Scala Actors: loop, react, and schedulers</title>
    <summary type="xhtml"><div xmlns="http://www.w3.org/1999/xhtml"><p>
One of the unfortunate aspects of many of the "published" (meaning blogged) <a href="http://www.scala-lang.org/node/242">Scala Actor</a> benchmarks out there is that they rarely pay much attention, if any, to the affects of seemingly idiomatic patterns on performance.  Some of the main culprits are:
</p>
<ol>
<li>react versus receive (event-based versus threaded)</li>
<li>loop/react versus recursive react</li>
<li>loop/receive versus receive/while</li>
<li>tweaking (or failing to tweak) the scheduler</li>
</ol>
<p>
I've been working on setting up a "benchmarking framework" in conjunction with experimenting with modifications to the underlying thread pool so that all the possible permutations are automatically tested.  What I have right now is a classic "ring" benchmark setup to permute the schedulers and loop/react versus recursive react.  The loop/react pattern is more idiomatic (or at least more common), but higher overhead, and it looks something like this:
</p>
<pre>loop {
  react {
    case Msg(m) =&gt; // do stuff
    case Stop =&gt; exit()
  }
}
</pre>
<p>
The reason it is high-overhead is that both loop and react raise control flow exceptions that result in the creation of new tasks for the thread pool when they are hit, so for each loop, two exceptions are raised and two tasks are executed.  There's overhead in both of the operations, especially raising the exceptions.  The recursive react pattern looks like this, so it can avoid the extra exception/task:
</p>
<pre>def rloop(): Unit = react {  //this would be called by the act() method
  case Msg(m) =&gt; {
    // do stuff
    rloop()
  }
  case Stop =&gt; // just drop out or call exit()
}
</pre>
<p>
Using loop instead of recursive react effectively doubles the number of tasks that the thread pool has to execute in order to accomplish the same amount of work, which in turn makes it so any overhead in the scheduler is far more pronounced when using loop.  Now, I should point out that the overhead really isn't that large, so if the actor is performing significant computations it will be lost in the noise.  But it's fairly common to have actors do fairly little with each message.  Here's some results from the ring benchmark using 10 rings of 10,000 actors passing a token around them 100 times before exiting.  I'm using multiple rings because otherwise there is no parallelism in the benchmark.  These are being run on my dual core Macbook.
</p>
<table border="1">
<tbody><tr>
  <th>Scheduler</th><th>ReactMethod</th><th>Time (sec)</th>
</tr><tr>
</tr><tr>
  <td>ManagedForkJoinScheduler</td><td>LoopReact</td><td>45.416058</td>
</tr>
<tr>
  <td>ManagedForkJoinScheduler</td><td>RecursiveReact</td><td>25.509482</td>
</tr>
<tr>
  <td>ForkJoinScheduler</td><td>LoopReact</td><td>65.268584</td>
</tr>
<tr>
  <td>ForkJoinScheduler</td><td>RecursiveReact</td><td>45.85605</td>
</tr>
<tr>
  <td>ResizableThreadPoolScheduler</td><td>LoopReact</td><td>98.084794</td>
</tr>
<tr>
  <td>ResizableThreadPoolScheduler</td><td>RecursiveReact</td><td>53.379757</td>
</tr>
</tbody></table>
<p>
The fork/join schedulers are faster than the ResizableThreadPoolScheduler because rather than have all of the worker threads pull tasks off of a single, shared queue; each thread maintains its own local dequeue where it can place tasks directly onto if they are generated while it is running a task.  This creates a kind of "fast path" for the tasks that involves much less overhead.
</p>
<p>
I believe the primary reason ManagedForkJoinScheduler is faster because ForkJoinScheduler does not always leverage the "fast path," even when in theory it could be used.  I'm unsure about some of the rationale behind it, but I know some of the time the fast path is bypassed probabilistically in order to reduce the chances of starvation causing deadlock in the presence of long running or blocking tasks.  ManagedForkJoinScheduler escapes this particular issue by more actively monitoring the underlying thread pool, and growing it when tasks are being starved.   The second reason, and I'm somewhat unsure of the actual degree of the affects, if that ForkJoinScheduler configures the underlying thread pool so that the threads work through the local dequeues in FIFO order, while ManagedForkJoinScheduler configures the pool such that the local dequeues are processed in LIFO order.  Processing in LIFO order allows the pool to take advantage of locality with regard to the tasks, basically assuming that the last task generated is the most likely to use data that's currently in cache, and thus reduce cache misses.
</p>
<p>
The benchmark outputs a lot more information than I captured in the above table.  If you'd like to run it, you can obtain the code <a href="https://bitbucket.org/eengbrec/managedforkjoinpool">here</a>.  The project uses <a href="http://code.google.com/p/simple-build-tool/">sbt</a>, so you'll need to have it working on your computer.  After you run update in sbt to download all of the dependencies, you can run the ring benchmark as follows:
</p>
<pre>$ sbt
[info] Building project ManagedForkJoinPool 1.0 against Scala 2.8.0
[info]    using ManagedForkJoinPoolProject with sbt 0.7.4 and Scala 2.7.7
&gt; ringbenchmark
[info] 
[info] == compile ==
[info]   Source analysis: 1 new/modified, 0 indirectly invalidated, 0 removed.
[info] Compiling main sources...
[info] Compilation successful.
[info]   Post-analysis: 79 classes.
[info] == compile ==
[info] 
[info] == copy-resources ==
[info] == copy-resources ==
[info] 
[info] == ringbenchmark ==
[info] RingBenchmark ManagedForkJoinScheduler LoopReact 2 ....output truncated...
</pre>
<p>
You can tweak the benchmarks by modifying the sbt project file.  If you do run them, I'm very interested in the results.
</p><div class="blogger-post-footer"><img alt="" height="1" src="https://blogger.googleusercontent.com/tracker/19725519-3926620988428095194?l=erikengbrecht.blogspot.com" width="1"/></div></div>
    </summary>
    <updated>2010-08-23T01:41:00Z</updated>
    <category scheme="http://www.blogger.com/atom/ns#" term="Scala"/>
    <category scheme="http://www.blogger.com/atom/ns#" term="Functional Programming"/>
    <category scheme="http://www.blogger.com/atom/ns#" term="actors"/>
    <category scheme="http://www.blogger.com/atom/ns#" term="programming"/>
    <category scheme="http://www.blogger.com/atom/ns#" term="benchmarks"/>
    <author>
      <name>Erik Engbrecht</name>
      <email>noreply@blogger.com</email>
    </author>
    <source>
      <id>tag:blogger.com,1999:blog-19725519</id>
      <author>
        <name>Erik Engbrecht</name>
        <email>noreply@blogger.com</email>
      </author>
      <link href="http://erikengbrecht.blogspot.com/" rel="alternate" type="text/html"/>
      <link href="http://erikengbrecht.blogspot.com/feeds/posts/default?alt=rss" rel="self" type="application/atom+xml"/>
      <subtitle>Thoughts and Essays on Systems Engineering and Software Engineering,  and IT</subtitle>
      <title>Erik Engbrecht's Blog</title>
      <updated>2010-09-08T02:00:44Z</updated>
    </source>
  </entry>

  <entry>
    <id>http://code.technically.us/post/989015835</id>
    <link href="http://code.technically.us/post/989015835" rel="alternate" type="text/html"/>
    <title>"This is a simple-build-tool plugin for compiling CoffeeScript files into their javascript..."</title>
    <summary type="xhtml"><div xmlns="http://www.w3.org/1999/xhtml">“This is a simple-build-tool plugin for compiling CoffeeScript files into their javascript conterparts.”<br/><br/> - <em><a href="http://groups.google.com/group/simple-build-tool/browse_thread/thread/6651aca5ada33151/d10935a0f53c042f?show_docid=d10935a0f53c042f&amp;pli=1">coffee-script-sbt-plugin</a></em></div>
    </summary>
    <updated>2010-08-21T20:39:14Z</updated>
    <category term="sbt"/>
    <category term="Plugins"/>
    <category term="CoffeeScript"/>
    <category term="Hells Yeah"/>
    <source>
      <id>http://code.technically.us/</id>
      <author>
        <name>Coderspiel</name>
      </author>
      <link href="http://tumblr.superfeedr.com/" rel="hub" type="text/html"/>
      <link href="http://code.technically.us/" rel="alternate" type="text/html"/>
      <link href="http://code.technically.us/rss" rel="self" type="application/rss+xml"/>
      <title>Coderspiel</title>
      <updated>2010-09-09T03:00:39Z</updated>
    </source>
  </entry>

  <entry>
    <id>tag:blogger.com,1999:blog-19725519.post-4428924252454371333</id>
    <link href="http://erikengbrecht.blogspot.com/2010/08/concurrency-benchmarking-actors-and-sbt.html" rel="alternate" type="text/html"/>
    <title>Concurrency Benchmarking, Actors, and sbt tricks</title>
    <summary type="xhtml"><div xmlns="http://www.w3.org/1999/xhtml"><p>
Have you ever noticed that other people's <a href="http://en.wikipedia.org/wiki/Benchmark_(computing)">microbenchmarks</a> tend to be hard to run and often impossible to duplicate?  And are frequently caveated to the hilt?  When it gets down to it, a benchmark is really an experiment, and ideally a scientific experiment.  That means all factors that are relevant to the results should be clearly recorded, and the tests should be easy for others to duplicate.
</p>
<h3>Custom sbt actions for benchmarks</h3>
<p>
In order to test and run benchmarks on the work I'm doing around creating a managed variant of the <a href="http://artisans-serverintellect-com.si-eioswww6.com/default.asp?W9">JSR-166y</a> <a href="http://gee.cs.oswego.edu/dl/jsr166/dist/jsr166ydocs/jsr166y/ForkJoinPool.html">ForkJoinPool</a> along with supporting infrastructure for use with <a href="http://www.scala-lang.org/node/242">Scala Actors</a>, I'm creating a <a href="https://bitbucket.org/eengbrec/managedforkjoinpool/src/tip/src/main/scala/actorbench/TestHarness.scala">test harness</a> that captures <a href="https://bitbucket.org/eengbrec/managedforkjoinpool/src/1cf3a55d2aa0/src/main/scala/actorbench/TestHarness.scala#cl-107">a host of environmental factors</a> about how it was run, and writing <a href="http://code.google.com/p/simple-build-tool/wiki/CustomActions">sbt actions</a> to make it easy to run the benchmarks and automatically permute the variables.
</p>
<p>
It still needs a lot of work, but I had some trouble figuring out a really basic task so I thought I'd share it.  Basically I wanted to build a <a href="http://simple-build-tool.googlecode.com/svn/artifacts/latest/api/sbt/TaskManager.Task.html">Task object</a> that consists of several tasks based on information in the project definition and permuted parameters.  It actually pretty easy, as you can see in the snippet below from my project definition:
</p>
<pre>  /** this task executes the PingPong benchmark using each available scheduler */
  lazy val pingpongbench = pingpongTaskList
  /** produces a sequence of run tasks using all the available schedulers  */
  def pingpongTaskList = {
    val pairs = 100
    val messagesPerPair = 10000
    val tasks = for(sched &lt;- schedulers) yield pingpongTask(sched, pairs, messagesPerPair)
    tasks.reduceLeft((a, b) =&gt; a &amp;&amp; b)
  }
</pre>
<p>You can see the whole file <a href="https://bitbucket.org/eengbrec/managedforkjoinpool/src/1cf3a55d2aa0/project/build/ManagedForkJoinPool.scala">here</a>.  Basically <code>Task</code> has an <code>&amp;&amp;</code> operator that essentially allows you to concatenate one task with another task.  This allows you to build a whole chain of tasks.  In the example above, I'm having it run the benchmark once for each scheduler configuration.  Soon, I'm going to make it permute other parameters.  But right now my test harness isn't playing nicely with the schedulers included in the Scala distribution, so first things first.</p>
<p>
There's also one other little customization, which is documented, but I think it's important for benchmarking.  By default, sbt runs your code in its own process.  This can cause <a href="http://code.google.com/p/simple-build-tool/wiki/RunningProjectCode">problems</a> with multithreaded code, especially if it doesn't terminate properly.  It also means the next benchmark to run has to content with any junk that the previous benchmark left around.  So I configured sbt to <a href="http://code.google.com/p/simple-build-tool/wiki/Forking">fork</a> new processes.  It just required one line:
</p>
<pre>override def fork = forkRun
</pre>
<h3>Important variables</h3>
<p>
Here's what I'm capturing for each run right now so that the results can all be dumped into a big spreadsheet for analysis.  I'd like to capture more information about the host machine, such as more information about the CPUs and the loading when the benchmark is being run, but haven't got that far yet.  Currently these are all captured from within the benchmark process, mostly using <a href="http://download.oracle.com/javase/6/docs/api/java/lang/System.html#getProperties()">system properties</a> and the <a href="http://download.oracle.com/javase/6/docs/api/java/lang/Runtime.html">Runtime</a> object.
</p>
<ol>
 <li>Test Name - obviously needed so that results from multiple benchmarks can be stored in the same file</li>
  <li> Scheduler - this is my primary variable right now, I want to run each benchmark with each scheduler while holding everything else constant</li>
  <li># of Cores/Processors - essential so that anyone looking at the results has an idea about the hardware used</li>
  <li>Java VM Name - different VMs can perform quite differently</li>
  <li>Java VM Version - performance characteristics change from version to version (usually getting better)</li>
  <li>Java Version - same reason as above, but this is probably the more publicly known version number</li>
  <li>Scala Version - this could be important in the future, as it becomes more common for different projects to be on different version of Scala</li>
  <li>OS Name and version - again, it can affect performance</li>
  <li>Processor Architecture</li>
  <li>Approximate Concurrency (number of simultaneously alive actors) - this allows us to examine concurrency levels versus resource consumption, more concurrency does not necessarily mean that more cores or threads would be helpful</li>
  <li>Approximate Parallelism (number of simultaneously runnable actors) - this measures how many cores/threads the benchmark can really keep busy&lt;/il&gt;
  </li><li>Approximate Total Messages - this estimates the amount of activity that takes place during the benchmark, generally the benchmarks I'm looking at contain very little logic because they are intended to measure overhead introduced by the framework</li>
  <li>Total Wall Clock Time (seconds) - as measured using nanoTime within the benchmark process</li>
  <li>Initial Thread and Maximum Observed Thread Count - used to examine automatic expansion of the thread pool</li>
  <li>Initial Free Memory and Minimum Observed Free Memory - threads use a fair amount of memory, so performance impacts may show up as pressure on the GC as well has contention for the CPU</li>
  <li>Initial and Maximum Observed Total Memory - threads use a lot of memory, so it's important to track usage</li>
  <li>Verbose - debugging output pretty much invalidates any of these tests</li>
</ol><div class="blogger-post-footer"><img alt="" height="1" src="https://blogger.googleusercontent.com/tracker/19725519-4428924252454371333?l=erikengbrecht.blogspot.com" width="1"/></div></div>
    </summary>
    <updated>2010-08-21T19:09:00Z</updated>
    <category scheme="http://www.blogger.com/atom/ns#" term="Scala"/>
    <category scheme="http://www.blogger.com/atom/ns#" term="actors"/>
    <category scheme="http://www.blogger.com/atom/ns#" term="sbt"/>
    <category scheme="http://www.blogger.com/atom/ns#" term="benchmarks"/>
    <category scheme="http://www.blogger.com/atom/ns#" term="concurrency"/>
    <author>
      <name>Erik Engbrecht</name>
      <email>noreply@blogger.com</email>
    </author>
    <source>
      <id>tag:blogger.com,1999:blog-19725519</id>
      <author>
        <name>Erik Engbrecht</name>
        <email>noreply@blogger.com</email>
      </author>
      <link href="http://erikengbrecht.blogspot.com/" rel="alternate" type="text/html"/>
      <link href="http://erikengbrecht.blogspot.com/feeds/posts/default?alt=rss" rel="self" type="application/atom+xml"/>
      <subtitle>Thoughts and Essays on Systems Engineering and Software Engineering,  and IT</subtitle>
      <title>Erik Engbrecht's Blog</title>
      <updated>2010-09-08T02:00:45Z</updated>
    </source>
  </entry>

  <entry>
    <id>http://code.technically.us/post/982400357</id>
    <link href="http://code.technically.us/post/982400357" rel="alternate" type="text/html"/>
    <title>You sound somewhat obsessed with fonts.</title>
    <summary type="xhtml"><div xmlns="http://www.w3.org/1999/xhtml"><img src="http://30.media.tumblr.com/tumblr_l7gdykKuDh1qb6dplo1_500.gif"/><br/><br/><p><a href="http://wondermark.com/650/">You sound somewhat obsessed with fonts.</a></p></div>
    </summary>
    <updated>2010-08-20T13:39:00Z</updated>
    <category term="Copperplate Gothic"/>
    <category term="Monotype Corsiva"/>
    <category term="Papyrus"/>
    <source>
      <id>http://code.technically.us/</id>
      <author>
        <name>Coderspiel</name>
      </author>
      <link href="http://tumblr.superfeedr.com/" rel="hub" type="text/html"/>
      <link href="http://code.technically.us/" rel="alternate" type="text/html"/>
      <link href="http://code.technically.us/rss" rel="self" type="application/rss+xml"/>
      <title>Coderspiel</title>
      <updated>2010-09-09T03:00:39Z</updated>
    </source>
  </entry>

  <entry xml:lang="en">
    <id>http://www.decodified.com/scala/2010/08/20/Using_Apache_Buildr_on_OS_X_10.6/</id>
    <link href="http://www.decodified.com/scala/2010/08/20/Using_Apache_Buildr_on_OS_X_10.6.html" rel="alternate" type="text/html"/>
    <title>Installing Apache Buildr on OS/X 10.6</title>
    <summary type="xhtml"><div xmlns="http://www.w3.org/1999/xhtml"><p>For my first larger, Scala-only project I just set up a brand-new project space.<br/>Normally all my projects have an IntelliJ IDEA project structure set up for the day-to-day work. However, I usually also include a paralleling project spec for some build system for creating the final deployment or distribution artifacts. For all my Java projects this is (and always has been)...</p></div>
    </summary>
    <updated>2010-08-20T07:00:00Z</updated>
    <category scheme="http://www.decodified.com/categories/scala" term="scala"/>
    <source>
      <id>http://www.decodified.com</id>
      <author>
        <name>Mathias</name>
      </author>
      <link href="http://www.decodified.com" rel="alternate" type="text/html"/>
      <link href="http://feeds.feedburner.com/decodified" rel="self" type="application/rss+xml"/>
      <link href="http://pubsubhubbub.appspot.com/" rel="hub" type="text/html"/>
      <rights>Copyright 2010, decodified.com</rights>
      <subtitle>between code and cleartext</subtitle>
      <title>decodified</title>
      <updated>2010-09-03T09:16:29Z</updated>
    </source>
  </entry>

  <entry xml:lang="en">
    <id>http://www.scala-lang.org/7373 at http://www.scala-lang.org</id>
    <link href="http://www.scala-lang.org/node/7373" rel="alternate" type="text/html"/>
    <title>Scala LiftOff Goes International</title>
    <summary type="xhtml"><div xmlns="http://www.w3.org/1999/xhtml"><p>Last year over 80 developers had a great time at the <a href="http://scalaliftoff.com/">Scala LiftOff</a> in San Francisco. Since then there has been a tremendous growth in the world wide Lift/Scala community and lots of excitement with the releases of Lift 2.0 and Scala 2.8.0. Scala LiftOff has gone international to allow more people to catch up with the latest developments and let more developers talk over the latest stuff. This year you can join other enthusiastic members of the Scala and Lift community in London, New York or San Francisco and find out what's going on. David Pollak, the power behind Lift, and many industry experts will be at all three while you will have a chance to meet Martin Odersky, the creator of Scala, at the London event. The first one is in September so you will need to register soon.</p></div>
    </summary>
    <updated>2010-08-19T15:02:15Z</updated>
    <author>
      <name>bagwell</name>
    </author>
    <source>
      <id>http://www.scala-lang.org/</id>
      <link href="http://www.scala-lang.org/" rel="alternate" type="text/html"/>
      <link href="http://www.scala-lang.org/rss.xml" rel="self" type="application/rss+xml"/>
      <title>The Scala Programming Language</title>
      <updated>2010-09-09T03:01:10Z</updated>
    </source>
  </entry>

  <entry xml:lang="en">
    <id>http://www.scala-lang.org/7364 at http://www.scala-lang.org</id>
    <link href="http://www.scala-lang.org/node/7364" rel="alternate" type="text/html"/>
    <title>What's new in Scala 2.8: Collections API</title>
    <summary type="xhtml"><div xmlns="http://www.w3.org/1999/xhtml"><p>Scala 2.8 has introduced a great number of improvements and additions. They are summarized in the <a href="http://www.scala-lang.org/node/7009">release notes</a>. Over the next weeks, we will publish a series of stories that explain the major new features one-by-one. We start this week with the Scala 2.8 collections API.</p><p>In the eyes of many, the new collections framework is the most significant change in Scala 2.8. Scala had collections before (and in fact the new framework is largely compatible with them). But it's only 2.8 that provides a common, uniform, and all-encompassing framework for collection types.</p></div>
    </summary>
    <updated>2010-08-18T12:36:55Z</updated>
    <author>
      <name>odersky</name>
    </author>
    <source>
      <id>http://www.scala-lang.org/</id>
      <link href="http://www.scala-lang.org/" rel="alternate" type="text/html"/>
      <link href="http://www.scala-lang.org/rss.xml" rel="self" type="application/rss+xml"/>
      <title>The Scala Programming Language</title>
      <updated>2010-09-09T03:01:10Z</updated>
    </source>
  </entry>

  <entry xml:lang="en-US">
    <id>tag:blog.getintheloop.eu,2010-08-18:1691</id>
    <link href="http://blog.getintheloop.eu/2010/8/18/native2ascii-plugin-for-sbt" rel="alternate" type="text/html"/>
    <title xml:lang="en-US">Native2Ascii plugin for SBT</title>
    <content type="xhtml" xml:lang="en-US"><div xmlns="http://www.w3.org/1999/xhtml"><p>As I have been doing quite a lot of localisation work recently, I thought it prudent to port the native2ascii tool over to <span class="caps">SBT</span> so that I didn’t constantly have to keep using it manually on the command line. If you are interested, you can grab the source code from <a href="http://github.com/timperrett/sbt-native2ascii-plugin">here</a></p>


	<p>If order to get started with the plugin add it to your Plugins.scala within your project:</p>


<pre><code>
  import sbt._
  class Plugins(info: ProjectInfo) extends PluginDefinition(info) {
    val n2a = "eu.getintheloop" % "sbt-native2ascii-plugin" % "0.1.0" 
  }
</code></pre>

	<p>...and then mix the Native2Ascii trait into your project:</p>


<pre><code>
  class SampleProject(info: ProjectInfo) 
    extends DefaultWebProject(info) 
    with Native2AsciiPlugin {
    ...
  }
</code></pre>

	<p>Ensure you have all your localization .txt files in src/main/i18n and by default they will be translated into your application resources folder in src/main/resources.</p>


	<p>Then, from your <span class="caps">SBT</span> prompt just hit:</p>


<code>
  &gt; native2ascii
</code>

	<p>All being well you should then see something like:</p>


<pre><code>
  [info] == native2ascii ==
  [info] Encoding '.txt' to '.properties' file(s) in src/main/resources
  [info] Translation complete.
  [info] == native2ascii ==
</code></pre></div>
    </content>
    <updated>2010-08-18T09:32:25Z</updated>
    <published>2010-08-18T09:32:00Z</published>
    <author>
      <name>timperrett</name>
    </author>
    <source>
      <id>tag:blog.getintheloop.eu,2010:mephisto/</id>
      <link href="http://blog.getintheloop.eu/feed/" rel="self" type="application/atom+xml"/>
      <link href="http://blog.getintheloop.eu/" rel="alternate" type="text/html"/>
      <title xml:lang="en-US">The Loop - Blog</title>
      <updated>2010-08-18T09:32:25Z</updated>
    </source>
  </entry>

  <entry>
    <id>tag:blogger.com,1999:blog-1673113361032868171.post-5759189149355697352</id>
    <link href="http://suereth.blogspot.com/feeds/5759189149355697352/comments/default" rel="replies" type="application/atom+xml"/>
    <link href="https://www.blogger.com/comment.g?blogID=1673113361032868171&amp;postID=5759189149355697352" rel="replies" type="text/html"/>
    <link href="http://www.blogger.com/feeds/1673113361032868171/posts/default/5759189149355697352" rel="edit" type="application/atom+xml"/>
    <link href="http://www.blogger.com/feeds/1673113361032868171/posts/default/5759189149355697352" rel="self" type="application/atom+xml"/>
    <link href="http://suereth.blogspot.com/2010/08/whats-state-of-jigsaw.html" rel="alternate" type="text/html"/>
    <title>What's the state of Jigsaw?</title>
    <content type="xhtml"><div xmlns="http://www.w3.org/1999/xhtml">I hadn't been paying close attention, but recently <a href="http://mail.openjdk.java.net/pipermail/jigsaw-dev/2010-August/001105.html">a few emails questioning the future of the jigsaw project</a> have been sent to the jigsaw-dev mailing list.  The last check-in posted to the mailing list was on June 8th, and was the tail-end of a flurry of check-ins from the jigsaw team.<br/><br/>The whole thing is rather curious, but without any specific word from Oracle, it's all speculation.   I have my own guesses, but it's probably best I keep those to myself for now.<div class="blogger-post-footer"><img alt="" height="1" src="https://blogger.googleusercontent.com/tracker/1673113361032868171-5759189149355697352?l=suereth.blogspot.com" width="1"/></div></div>
    </content>
    <updated>2010-08-18T02:41:09Z</updated>
    <published>2010-08-18T02:41:00Z</published>
    <category scheme="http://www.blogger.com/atom/ns#" term="java"/>
    <category scheme="http://www.blogger.com/atom/ns#" term="jigasw"/>
    <category scheme="http://www.blogger.com/atom/ns#" term="oracle"/>
    <author>
      <name>J. Suereth</name>
      <email>noreply@blogger.com</email>
      <uri>http://www.blogger.com/profile/10176429810160937559</uri>
    </author>
    <source>
      <id>tag:blogger.com,1999:blog-1673113361032868171</id>
      <author>
        <name>J. Suereth</name>
        <email>noreply@blogger.com</email>
        <uri>http://www.blogger.com/profile/10176429810160937559</uri>
      </author>
      <link href="http://suereth.blogspot.com/feeds/posts/default" rel="http://schemas.google.com/g/2005#feed" type="application/atom+xml"/>
      <link href="http://www.blogger.com/feeds/1673113361032868171/posts/default" rel="self" type="application/atom+xml"/>
      <link href="http://suereth.blogspot.com/" rel="alternate" type="text/html"/>
      <link href="http://pubsubhubbub.appspot.com/" rel="hub" type="text/html"/>
      <link href="http://www.blogger.com/feeds/1673113361032868171/posts/default?start-index=26&amp;max-results=25" rel="next" type="application/atom+xml"/>
      <subtitle>My thoughts and/or rants on Software Development.</subtitle>
      <title>Rants, Raves and Ridicule</title>
      <updated>2010-09-06T12:26:25Z</updated>
    </source>
  </entry>

  <entry xml:lang="en">
    <id>http://www.scala-lang.org/7357 at http://www.scala-lang.org</id>
    <link href="http://www.scala-lang.org/node/7357" rel="alternate" type="text/html"/>
    <title>Scala Training</title>
    <summary type="xhtml"><div xmlns="http://www.w3.org/1999/xhtml"><p>Skills Matter and Xebia will be providing a series of Scala training sessions starting in October and initially located in London, Amsterdam and Paris. In response to the growing demand Scala courses are being made available through local, well established commercial partners. The courses have been designed by Martin Odersky and will be delivered by him and Iulian Dragos.</p> <p>These two day courses are excellent for developers or systems architects wanting to learn about Scala and need to understand how it can fit into their development tool-bag. Next courses are available in:</p> <p>London, UK 4/5 October 2010 Skills Matter. <a href="http://skillsmatter.com/course/scala/bject-oriented-meets-functional-an-exploaration-of-scala">Learn more about the course and register.<br/> </a>Amsterdam, NL 14/15 October 2010 Xebia. <a href="http://www.xebia.com/scalatraining">Learn more about the course and register.</a></p></div>
    </summary>
    <updated>2010-08-17T14:17:02Z</updated>
    <author>
      <name>bagwell</name>
    </author>
    <source>
      <id>http://www.scala-lang.org/</id>
      <link href="http://www.scala-lang.org/" rel="alternate" type="text/html"/>
      <link href="http://www.scala-lang.org/rss.xml" rel="self" type="application/rss+xml"/>
      <title>The Scala Programming Language</title>
      <updated>2010-09-09T03:01:10Z</updated>
    </source>
  </entry>

  <entry>
    <id>tag:blogger.com,1999:blog-7317245822288637185.post-6613929915055468887</id>
    <link href="http://grahamhackingscala.blogspot.com/feeds/6613929915055468887/comments/default" rel="replies" type="application/atom+xml"/>
    <link href="http://grahamhackingscala.blogspot.com/2010/08/keyboard-navigation-search-results.html#comment-form" rel="replies" type="text/html"/>
    <link href="http://www.blogger.com/feeds/7317245822288637185/posts/default/6613929915055468887?v=2" rel="edit" type="application/atom+xml"/>
    <link href="http://www.blogger.com/feeds/7317245822288637185/posts/default/6613929915055468887?v=2" rel="self" type="application/atom+xml"/>
    <link href="http://feedproxy.google.com/~r/blogspot/vnby/~3/6cNqY87aSks/keyboard-navigation-search-results.html" rel="alternate" type="text/html"/>
    <title>Things I Love About IntelliJ IDEA: Keyboard Navigation of Search Results</title>
    <content type="xhtml"><div xmlns="http://www.w3.org/1999/xhtml">One of the things that really helps IntelliJ IDEA deliver on its claim of increased productivity is the JetBrains guys' fixation with keyboard navigation and one area where they've hit a home run with this is in navigating search results. The idea is actually really simple: you can navigate search results using the keyboard: Ctrl-Alt-Down to go to the next result, Ctrl-Alt-Up to go to the previous one.<br/><br/>If I were just to end the blog there, I'd probably have a throng of Eclipse users banging on my door telling me you can do the same thing in Eclipse: "Just click in the Search View, then use Ctrl+. and Ctrl+," they'd say, and they'd be right. But it's the "Just click in the Search View" part which is all wrong. I shouldn't have to click anywhere. Someone might point out that I can can change the focus between different Views using Ctrl-F7, which again would be correct and would again miss the point.<br/><br/>The point is: I'm coding. I'm writing code; I'm searching code; I'm changing code. I don't want to focus on a Seach View, I want to focus on my code. In IntelliJ, I don't even have to have the Search pane visible to be able to browse through the results. I just have to hit Ctrl-Alt-Down and I'm at the next result, ready to edit. In Eclipse, if the window focus is in the Editor and I want to go to the next Search result, I either have to use the mouse to select and double-click on the next result, or I have to change to the Search View (Ctrl-F7, including pop-up View selector window), press down to select the next result, then press Enter to return to the Editor.<br/><br/>This is one of those niggles in Eclipse about which I like to say, "The guy who wrote the Editor plug-in didn't talk to the guy who wrote the Search plug-in". I often get the feeling that while IDEA is the product of a close-knit team aiming to produce a seamlessly integrated code-authoring masterpiece, Eclipse is just a bunch of code-related tools that have been slapped inside the same GUI without enough thought as to how those tools should play well together.<div class="blogger-post-footer"><img alt="" height="1" src="https://blogger.googleusercontent.com/tracker/7317245822288637185-6613929915055468887?l=grahamhackingscala.blogspot.com" width="1"/></div>
<p><a href="http://feedads.g.doubleclick.net/~a/Lh6GFhNckSJaW0lvk3SVe2sCSdY/0/da"><img border="0" ismap="true" src="http://feedads.g.doubleclick.net/~a/Lh6GFhNckSJaW0lvk3SVe2sCSdY/0/di"/></a><br/>
<a href="http://feedads.g.doubleclick.net/~a/Lh6GFhNckSJaW0lvk3SVe2sCSdY/1/da"><img border="0" ismap="true" src="http://feedads.g.doubleclick.net/~a/Lh6GFhNckSJaW0lvk3SVe2sCSdY/1/di"/></a></p><img height="1" src="http://feeds.feedburner.com/~r/blogspot/vnby/~4/6cNqY87aSks" width="1"/></div>
    </content>
    <updated>2010-08-17T03:26:50Z</updated>
    <published>2010-08-17T03:22:00Z</published>
    <category scheme="http://www.blogger.com/atom/ns#" term="intellij"/>
    <category scheme="http://www.blogger.com/atom/ns#" term="plug-in"/>
    <category scheme="http://www.blogger.com/atom/ns#" term="keyboard"/>
    <category scheme="http://www.blogger.com/atom/ns#" term="idea"/>
    <category scheme="http://www.blogger.com/atom/ns#" term="eclipse"/>
    <category scheme="http://www.blogger.com/atom/ns#" term="shortcuts"/>
    <category scheme="http://www.blogger.com/atom/ns#" term="navigation"/><feedburner:origLink xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0">http://grahamhackingscala.blogspot.com/2010/08/keyboard-navigation-search-results.html</feedburner:origLink>
    <author>
      <name>Grazer</name>
      <email>noreply@blogger.com</email>
      <uri>http://www.blogger.com/profile/00435359638152521056</uri>
    </author>
    <source>
      <id>tag:blogger.com,1999:blog-7317245822288637185</id>
      <author>
        <name>Grazer</name>
        <email>noreply@blogger.com</email>
        <uri>http://www.blogger.com/profile/00435359638152521056</uri>
      </author>
      <link href="http://grahamhackingscala.blogspot.com/feeds/posts/default" rel="http://schemas.google.com/g/2005#feed" type="application/atom+xml"/>
      <link href="http://grahamhackingscala.blogspot.com/" rel="alternate" type="text/html"/>
      <link href="http://feeds.feedburner.com/blogspot/vnby" rel="self" type="application/atom+xml"/>
      <link href="http://pubsubhubbub.appspot.com/" rel="hub" type="text/html"/>
      <subtitle>The point of "Graham Hacking Scala" is to share with you my knowledge of and experience with the Scala programming language. The blog will contain everything from introductions to basic features through to in-depth analysis of complex techniques and problems. When I make mistakes, you will learn from my mistakes. When I discover cool features, you will learn about them, too.</subtitle>
      <title>Graham Hacking Scala</title>
      <updated>2010-09-04T16:58:00Z</updated>
    </source>
  </entry>

  <entry xml:lang="en">
    <id>http://codemonkeyism.com/?p=1939</id>
    <link href="http://feedproxy.google.com/~r/stephansblog/~3/s66QNOWgPj0/" rel="alternate" type="text/html"/>
    <link href="http://codemonkeyism.com/interview-dsl-nosql-scala-practitioner-debasish-ghosh/#comments" rel="replies" type="text/html"/>
    <link href="http://codemonkeyism.com/interview-dsl-nosql-scala-practitioner-debasish-ghosh/feed/atom/" rel="replies" type="application/atom+xml"/>
    <title xml:lang="en">Interview with DSL, NoSQL and Scala Practitioner Debasish Ghosh</title>
    <summary type="xhtml" xml:lang="en"><div xmlns="http://www.w3.org/1999/xhtml">This interview is with Debasish Ghosh. He’s writing the successful blog Ruminations of a Programmer with the tag line “A programmer’s blog – will deal with everything that relates to a programmer. Occasionally, it will contain some humour, some politics and some sport news.”.
Name: Debasish Ghosh (dghosh@acm.org)
Blog: http://debasishg.blogspot.com
Twitter: @debasishg
Github: http://github.com/debasishg
Tell us something about you (what [...]<img height="1" src="http://feeds.feedburner.com/~r/stephansblog/~4/s66QNOWgPj0" width="1"/></div>
    </summary>
    <updated>2010-08-16T15:01:04Z</updated>
    <published>2010-08-16T15:01:04Z</published>
    <category scheme="http://codemonkeyism.com" term="Java"/><feedburner:origLink xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0">http://codemonkeyism.com/interview-dsl-nosql-scala-practitioner-debasish-ghosh/</feedburner:origLink>
    <author>
      <name>stephan</name>
      <uri>http://codemonkeyism.com</uri>
    </author>
    <source>
      <id>http://codemonkeyism.com/feed/atom/</id>
      <link href="http://codemonkeyism.com" rel="alternate" type="text/html"/>
      <link href="http://feeds.feedburner.com/stephansblog" rel="self" type="application/atom+xml"/>
      <link href="http://pubsubhubbub.appspot.com/" rel="hub" type="text/html"/>
      <title xml:lang="en">Code Monkeyism</title>
      <updated>2010-09-08T05:05:52Z</updated>
    </source>
  </entry>

  <entry xml:lang="en">
    <id>http://www.decodified.com/parboiled/2010/08/16/parboiled_for_scala/</id>
    <link href="http://www.decodified.com/parboiled/2010/08/16/parboiled_for_scala.html" rel="alternate" type="text/html"/>
    <title>parboiled for Scala</title>
    <summary type="xhtml"><div xmlns="http://www.w3.org/1999/xhtml"><p>The recently released <a href="http://github.com/sirthias/parboiled/downloads" title="parboiled download page"><em>parboiled</em> version 0.9.8</a> comes with a brand-new feature that will hopefully make <em>parboiled</em> an attractive tool for an even larger developer community: a Scala facade.<br/>Before v0.9.8 <em>parboiled</em> was a pure-Java library written mainly for Java developers. It basically consisted of two things, an efficient recursive-descent <a href="http://en.wikipedia.org/wiki/Parsing_expression_grammar" title="PEG on Wikipedia">PEG</a> parsing engine and an...</p></div>
    </summary>
    <updated>2010-08-16T07:00:00Z</updated>
    <category scheme="http://www.decodified.com/categories/parboiled" term="parboiled"/>
    <source>
      <id>http://www.decodified.com</id>
      <author>
        <name>Mathias</name>
      </author>
      <link href="http://www.decodified.com" rel="alternate" type="text/html"/>
      <link href="http://feeds.feedburner.com/decodified" rel="self" type="application/rss+xml"/>
      <link href="http://pubsubhubbub.appspot.com/" rel="hub" type="text/html"/>
      <rights>Copyright 2010, decodified.com</rights>
      <subtitle>between code and cleartext</subtitle>
      <title>decodified</title>
      <updated>2010-09-03T09:16:29Z</updated>
    </source>
  </entry>

  <entry>
    <id>tag:blogger.com,1999:blog-178174920347765771.post-3386485961399223</id>
    <link href="http://james-iry.blogspot.com/2010/08/sometime-in-1977.html" rel="alternate" type="text/html"/>
    <title>Sometime in 1977</title>
    <summary>Kernighan: "I know, let's open the book with a program that displays 'hello, world.'"
Ritchie: "Great idea! I'll start the patent search."</summary>
    <updated>2010-08-13T20:18:00Z</updated>
    <category scheme="http://www.blogger.com/atom/ns#" term="humor"/>
    <author>
      <name>James Iry</name>
      <email>noreply@blogger.com</email>
    </author>
    <source>
      <id>tag:blogger.com,1999:blog-178174920347765771</id>
      <author>
        <name>James Iry</name>
        <email>noreply@blogger.com</email>
      </author>
      <link href="http://james-iry.blogspot.com/" rel="alternate" type="text/html"/>
      <link href="http://james-iry.blogspot.com/feeds/posts/default?alt=rss" rel="self" type="application/atom+xml"/>
      <subtitle>An exploration of software development.</subtitle>
      <title>One Div Zero</title>
      <updated>2010-09-03T03:01:02Z</updated>
    </source>
  </entry>

  <entry>
    <id>http://richard.dallaway.com/london-7-8-oct-2010-scala-lift-off</id>
    <link href="http://richard.dallaway.com/london-7-8-oct-2010-scala-lift-off" rel="alternate" type="text/html"/>
    <title>London, 7-8 Oct 2010: Scala Lift Off</title>
    <summary type="xhtml"><div xmlns="http://www.w3.org/1999/xhtml"><p>
	</p><p><a href="http://www.flickr.com/photos/d6y/sets/72157619282779995/with/3601476086/" title="Sessions by d6y, on Flickr"><img alt="Sessions" height="375" src="http://farm4.static.flickr.com/3625/3601476086_fb5a49263b.jpg" width="500"/></a></p>
<p>I have my ticket. <a href="http://skillsmatter.com/event/scala/scala-lift-off-london-2010/wd-1044">How about you?</a>  It's £150 at the moment.</p>
<p>What we're looking at here is a two day unconference, meaning we get a chance to learn about things we're interested in by figuring it out on the day, talking to people, rather than being lectured at.  I thoroughly enjoyed the Scala Lift Off last year in San Francisco, so I'm looking forward to the London one.  Especially as it close by, rather than <a href="http://www.happyzebra.com/distance-calculator/Brighton-to-San%20Francisco.php">8,720km</a> away.</p>
	
<p/>

<p><a href="http://richard.dallaway.com/london-7-8-oct-2010-scala-lift-off">Permalink</a> 

	| <a href="http://richard.dallaway.com/london-7-8-oct-2010-scala-lift-off#comment">Leave a comment  »</a>

</p></div>
    </summary>
    <updated>2010-08-13T12:16:00Z</updated>
    <source>
      <id>http://richard.dallaway.com</id>
      <author>
        <name>Richard Dallaway</name>
      </author>
      <link href="http://richard.dallaway.com" rel="alternate" type="text/html"/>
      <link href="http://posterous.com/api/sup_update#7a489faff" rel="http://api.friendfeed.com/2008/03#sup" type="application/json"/>
      <link href="http://richard.dallaway.com/rss.xml" rel="self" type="application/atom+xml"/>
      <link href="http://posterous.superfeedr.com" rel="hub" type="text/html"/>
      <subtitle>It's mostly technical stuff here. Mostly.</subtitle>
      <title>Richard Dallaway</title>
      <updated>2010-09-03T08:00:54Z</updated>
    </source>
  </entry>

  <entry>
    <id>http://richard.dallaway.com/if-you-like-web-mvc-youll-probably-like-the-p</id>
    <link href="http://richard.dallaway.com/if-you-like-web-mvc-youll-probably-like-the-p" rel="alternate" type="text/html"/>
    <title>If you like web MVC, you'll probably like the Play web framework.</title>
    <summary type="xhtml"><div xmlns="http://www.w3.org/1999/xhtml"><p>
	</p><p><a href="http://posterous.com/getfile/files.posterous.com/temp-2010-08-13/ukstbmgeyexIkGzEnDasmDlngFuDlweBvFpaAJvInBusrwAdihdApsyzdhtd/IMG_0004.JPG.scaled1000.jpg"><img height="403" src="http://posterous.com/getfile/files.posterous.com/temp-2010-08-13/ukstbmgeyexIkGzEnDasmDlngFuDlweBvFpaAJvInBusrwAdihdApsyzdhtd/IMG_0004.JPG.scaled500.jpg" width="500"/></a>
</p>
<p> </p>
<p>Play is a MVC, convention-based, stateless web framework for Java with growing support for Scala too.</p>
<p>It's not for me as I can't face going back to MVC and the kinds of presentation languages they use. Having said that, if you like MVC, and you're not already using Grails or Rails or a similar framework, I strongly urge you to <a href="http://www.playframework.org/">look at Play</a> as there's some nice technology in there. </p>
<p>Everything I know about Play comes from <a href="http://twitter.com/vigosun">Rustem Suniev</a>'s talk for the <a href="http://lsug.org/">London Scala User Group</a> at Skilsmatter on Wednesday. The <a href="http://skillsmatter.com/podcast/scala/scala-podcast-intro-to-play/rl-890">slides and video are already on-line</a> and they contain a really nice live-coding demo of Play which gave me a good sense of what the framework is about.  Nice work—and pizza courtesy of <a href="http://www.autoquake.com/">autoquake.com</a> (who <a href="http://www.autoquake.com/jobs">are hiring</a>).</p>
<p>One comment I will make is that Play pushes it's stateless-ness prominently. For many of us I suspect our default position is that stateful=bad and stateless=good.  That sounds sane, but you probably do need some state in your application, and you have to deal with it somehow, or push the issue somewhere, which leaves me feeling that state v. stateless thing is all a bit more complicated that we often think it is.  It certainly does not automatically mean better scaling or performance, but there are definite positives to it.  I'm glad to see the Play community <a href="http://groups.google.com/group/play-framework/browse_thread/thread/ac9dd976cb284bad/fe7beddf7fabcc38?lnk=gst&amp;q=stateful#fe7beddf7fabcc38">discussing state</a> and <a href="http://groups.google.com/group/play-framework/browse_thread/thread/27825e8c864add60/b7d99cf77cc4dd2c?lnk=gst&amp;q=stateful#b7d99cf77cc4dd2c">exploring some nice ideas</a>.  Just don't assume a label of "stateless" solves all your scaling problems—if you're lucky enough to have any :-)</p>
<p> </p>
	
<p/>

<p><a href="http://richard.dallaway.com/if-you-like-web-mvc-youll-probably-like-the-p">Permalink</a> 

	| <a href="http://richard.dallaway.com/if-you-like-web-mvc-youll-probably-like-the-p#comment">Leave a comment  »</a>

</p></div>
    </summary>
    <updated>2010-08-13T10:18:00Z</updated>
    <source>
      <id>http://richard.dallaway.com</id>
      <author>
        <name>Richard Dallaway</name>
      </author>
      <link href="http://richard.dallaway.com" rel="alternate" type="text/html"/>
      <link href="http://posterous.com/api/sup_update#7a489faff" rel="http://api.friendfeed.com/2008/03#sup" type="application/json"/>
      <link href="http://richard.dallaway.com/rss.xml" rel="self" type="application/atom+xml"/>
      <link href="http://posterous.superfeedr.com" rel="hub" type="text/html"/>
      <subtitle>It's mostly technical stuff here. Mostly.</subtitle>
      <title>Richard Dallaway</title>
      <updated>2010-09-03T08:00:53Z</updated>
    </source>
  </entry>

  <entry>
    <id>http://code.technically.us/post/943401924</id>
    <link href="http://code.technically.us/post/943401924" rel="alternate" type="text/html"/>
    <title>"C2DM created a nice opportunity for us to pull together different Google developer tools to create a..."</title>
    <summary type="xhtml"><div xmlns="http://www.w3.org/1999/xhtml">“C2DM created a nice opportunity for us to pull together different Google developer tools to create a simple but useful application to enable users to push links and other information from their desktop / laptop to their phone.”<br/><br/> - <em><a href="http://android-developers.blogspot.com/2010/08/powering-chrome-to-phone-with-android.html">Powering Chrome to Phone with Android to Device Messaging</a></em></div>
    </summary>
    <updated>2010-08-12T19:20:54Z</updated>
    <category term="Android"/>
    <category term="Chrome"/>
    <category term="Google"/>
    <category term="Push"/>
    <category term="ADB"/>
    <source>
      <id>http://code.technically.us/</id>
      <author>
        <name>Coderspiel</name>
      </author>
      <link href="http://tumblr.superfeedr.com/" rel="hub" type="text/html"/>
      <link href="http://code.technically.us/" rel="alternate" type="text/html"/>
      <link href="http://code.technically.us/rss" rel="self" type="application/rss+xml"/>
      <title>Coderspiel</title>
      <updated>2010-09-09T03:00:39Z</updated>
    </source>
  </entry>

  <entry>
    <id>http://code.technically.us/post/942542158</id>
    <link href="http://code.technically.us/post/942542158" rel="alternate" type="text/html"/>
    <title>Brendan McAdams gives an introduction to MongoDB and the...</title>
    <summary type="xhtml"><div xmlns="http://www.w3.org/1999/xhtml">&lt;object data="http://vimeo.com/moogaloop.swf" height="225" type="application/x-shockwave-flash" width="400"&gt;&lt;param name="allowscriptaccess" value="always"&gt;&lt;param name="allowfullscreen" value="true"&gt;&lt;param name="movie" value="http://vimeo.com/moogaloop.swf"&gt;&lt;param name="flashvars" value="clip_id=14090025&amp;amp;color=00adef&amp;amp;fullscreen=1&amp;amp;server=vimeo.com&amp;amp;show_byline=1&amp;amp;show_portrait=1&amp;amp;show_title=1"&gt;&lt;/object&gt;<br/><br/><p><a href="http://vimeo.com/14090025">Brendan McAdams gives an introduction</a> to MongoDB and the libraries available for using it with Scala.</p></div>
    </summary>
    <updated>2010-08-12T15:29:47Z</updated>
    <category term="Scala"/>
    <category term="MongoDB"/>
    <category term="NoSQL"/>
    <category term="rit"/>
    <category term="Meetups"/>
    <category term="Videos"/>
    <source>
      <id>http://code.technically.us/</id>
      <author>
        <name>Coderspiel</name>
      </author>
      <link href="http://tumblr.superfeedr.com/" rel="hub" type="text/html"/>
      <link href="http://code.technically.us/" rel="alternate" type="text/html"/>
      <link href="http://code.technically.us/rss" rel="self" type="application/rss+xml"/>
      <title>Coderspiel</title>
      <updated>2010-09-09T03:00:39Z</updated>
    </source>
  </entry>

  <entry>
    <id>http://code.technically.us/post/942531598</id>
    <link href="http://code.technically.us/post/942531598" rel="alternate" type="text/html"/>
    <title>Doug Tangren presents the Unfiltered toolkit for serving HTTP...</title>
    <summary type="xhtml"><div xmlns="http://www.w3.org/1999/xhtml">&lt;object data="http://vimeo.com/moogaloop.swf" height="225" type="application/x-shockwave-flash" width="400"&gt;&lt;param name="allowscriptaccess" value="always"&gt;&lt;param name="allowfullscreen" value="true"&gt;&lt;param name="movie" value="http://vimeo.com/moogaloop.swf"&gt;&lt;param name="flashvars" value="clip_id=14042004&amp;amp;color=00adef&amp;amp;fullscreen=1&amp;amp;server=vimeo.com&amp;amp;show_byline=1&amp;amp;show_portrait=1&amp;amp;show_title=1"&gt;&lt;/object&gt;<br/><br/><p><a href="http://vimeo.com/14042004">Doug Tangren presents</a> the <a href="http://github.com/n8han/unfiltered">Unfiltered</a> toolkit for serving HTTP requests in Scala.</p></div>
    </summary>
    <updated>2010-08-12T15:26:00Z</updated>
    <category term="Scala"/>
    <category term="Web"/>
    <category term="HTTP"/>
    <category term="softprops"/>
    <category term="Videos"/>
    <category term="Meetups"/>
    <source>
      <id>http://code.technically.us/</id>
      <author>
        <name>Coderspiel</name>
      </author>
      <link href="http://tumblr.superfeedr.com/" rel="hub" type="text/html"/>
      <link href="http://code.technically.us/" rel="alternate" type="text/html"/>
      <link href="http://code.technically.us/rss" rel="self" type="application/rss+xml"/>
      <title>Coderspiel</title>
      <updated>2010-09-09T03:00:39Z</updated>
    </source>
  </entry>

  <entry xml:lang="en">
    <id>http://www.scala-ide.org/?p=102</id>
    <link href="http://www.scala-ide.org/2010/08/not-a-release-but-new-and-noteworthy-even-so/" rel="alternate" type="text/html"/>
    <link href="http://www.scala-ide.org/2010/08/not-a-release-but-new-and-noteworthy-even-so/#comments" rel="replies" type="text/html"/>
    <link href="http://www.scala-ide.org/2010/08/not-a-release-but-new-and-noteworthy-even-so/feed/atom/" rel="replies" type="application/atom+xml"/>
    <title xml:lang="en">Not a release, but New and Noteworthy even so …</title>
    <summary xml:lang="en">Now that the dust has settled on the Scala 2.8.0.final release, we have some breathing space to think about moving the Scala IDE for Eclipse on towards it’s first release independently of the release of the Scala toolchain — you’ll recall that a big part of the motivation for the move from SVN at EPFL [...]</summary>
    <content type="xhtml" xml:lang="en"><div xmlns="http://www.w3.org/1999/xhtml"><p>Now that the dust has settled on the <a href="http://www.scala-lang.org/node/7009">Scala 2.8.0.final release</a>, we have some breathing space to think about moving the Scala IDE for Eclipse on towards it’s first release independently of the release of the Scala toolchain — you’ll <a href="http://www.scala-ide.org/2010/05/on-the-move/">recall</a> that a big part of the motivation for the move from <a href="http://lampsvn.epfl.ch/trac/scala/wiki">SVN at EPFL</a> to git at <a href="http://blog.assembla.com/assemblablog/tabid/12618/bid/12905/Featured-Open-Source-Project-Scala-IDE-for-Eclipse.aspx">Assembla</a> was to allow the IDE release cycle to be decoupled from the release cycle of the language — now it’s time to take advantage of that.</p>
<p>One part of the decoupling process has been rebooting the version numbering scheme for the IDE. We have three sets of versions to juggle with — the Scala toolchain version, the Eclipse version and the version of the SDT itself. Previously it made sense for the SDT to share it’s version number with the Scala toolchain, but that doesn’t work now that the two can move independently. So, to celebrate the birth of the Scala IDE for Eclipse as an independent open source project in a new OSGi namespace (org.scala-ide rather than ch.epfl.lamp), we’re starting from scratch and are currently at 1.0.0-SNAPSHOT heading for a 1.0.0 release. Readers who have been following the nightly updates for a while will be relieved to know that care has been taken to ensure that upgrades should be smooth despite change of namespace and the decrease in the version number.</p>
<p>Astute readers will have noticed a Maven-ish tinge to the new versioning scheme. That’s no accident, and I’m delighted to report that the move from an Ant-based build to a <a href="http://tycho.sonatype.org/">Tycho/Maven 3.0</a> based build is now complete and has been a more or less unqualified success. In particular, Tycho’s ability to manage the Eclipse target platform dependencies and build intricacies has been of enormous benefit — without it the <a href="http://www.scala-ide.org/2010/07/experimental-support-for-eclipse-helios-just-landed/">Helios build</a> would have taken even longer to arrive. The magic that is git has also paid off here as it’s allowing us to develop a Helios-specific branch with an ease that I would previously have thought impossible.</p>
<p>We still have a little way to go before that first release (I’ll post on the release plan and timetable shortly) but in the meantime I’d like to give you an update on current developments. So, without further ado …</p>
<h4>New and Noteworthy</h4>
<p/>
<h3>Refactoring Support</h3>
<p><a href="http://scala-ide.assembla.com/profile/misto">Mirko Stocker</a>’s <a href="http://scala-refactoring.org/">Scala Refactoring framework</a> is now included in the SDT. Currently there is support for <a href="http://scala-refactoring.org/rename/">Rename</a>, including in-place renaming of local identifiers:</p>
<p><a href="http://www.scala-ide.org/wp-content/uploads/2010/08/in-place-local-rename1.png"><img alt="In-place local rename" class="alignleft size-full wp-image-222" height="75" src="http://www.scala-ide.org/wp-content/uploads/2010/08/in-place-local-rename1.png" title="in-place-local-rename" width="347"/></a></p>
<p>We have an <a href="http://scala-refactoring.org/extract-method/">Extract Method</a> refactoring:</p>
<p><a href="http://www.scala-ide.org/wp-content/uploads/2010/08/extract-method-refactoring1.png"><img alt="Extract method refactoring" class="alignleft size-full wp-image-225" height="255" src="http://www.scala-ide.org/wp-content/uploads/2010/08/extract-method-refactoring1.png" title="extract-method-refactoring" width="661"/></a></p>
<p>and an <a href="http://scala-refactoring.org/inline-local/">Inline Local</a> refactoring:</p>
<p><a href="http://www.scala-ide.org/wp-content/uploads/2010/08/inline-refactoring1.png"><img alt="Inline refactoring" class="alignleft size-full wp-image-226" height="216" src="http://www.scala-ide.org/wp-content/uploads/2010/08/inline-refactoring1.png" title="inline-refactoring" width="661"/></a></p>
<p>We also have an <a href="http://scala-refactoring.org/extract-local/">Extract Local</a> refactoring and the beginnings of <a href="http://scala-refactoring.org/organize-imports/">Organize Imports</a> — so far existing imports will be tidied, but adding and removing imports is still work in progress.</p>
<p>Mirko’s site and <a href="http://scala-refactoring.org/documentation/">thesis</a> goes into a lot more detail, but in summary he’s done a fantastic job of separating out the lexical noise so that authors of refactorings can concentrate on the essence of the transformations involved without being distracted by whitespace or comment issues. The refactoring API is based on the standard scalac AST and is IDE-independent — we’d both love to see people contribute refactorings whether or not they’re Eclipse users.</p>
<h3>Formatting</h3>
<p><a href="http://scala-ide.assembla.com/profile/MattRussell">Matt Russell</a>’s Scala Formatter <a href="http://scala-ide.assembla.com/wiki/show/scalariform">Scalariform</a> is also now included.</p>
<p>Before:</p>
<p><a href="http://www.scala-ide.org/wp-content/uploads/2010/08/formatting-before1.png"><img alt="Formatting before" class="alignleft size-full wp-image-227" height="155" src="http://www.scala-ide.org/wp-content/uploads/2010/08/formatting-before1.png" title="formatting-before" width="203"/></a></p>
<p>After:</p>
<p><a href="http://www.scala-ide.org/wp-content/uploads/2010/08/formatting-after1.png"><img alt="Formatting after" class="alignleft size-full wp-image-228" height="152" src="http://www.scala-ide.org/wp-content/uploads/2010/08/formatting-after1.png" title="formatting-after" width="196"/></a></p>
<p>As you can see, it does a good job of formatting XML literals as well as ordinary Scala source. Like Mirko’s refactoring work, Scalariform has an IDE independent core and we’d welcome contributions from all parties.</p>
<h3>Mark Occurrences</h3>
<p>Matt has also contributed an implementation of Mark Occurrences which will be familiar to users of Eclipse’s Java tooling — this is somthing I’ve always found invaluable:</p>
<p><a href="http://www.scala-ide.org/wp-content/uploads/2010/08/mark-occurrences1.png"><img alt="Mark occurrences" class="alignleft size-full wp-image-229" height="121" src="http://www.scala-ide.org/wp-content/uploads/2010/08/mark-occurrences1.png" title="mark-occurrences" width="511"/></a></p>
<h3>Code Templates</h3>
<p><a href="http://scala-ide.assembla.com/profile/david.bernard.31">David Bernard</a> has added support for code templates for common boilerplate and which are offered as completion proposals in the Scala editor in the same way that Java code templates are presented the Java editor.</p>
<p>Requesting completion of a code template for a main method:</p>
<p><a href="http://www.scala-ide.org/wp-content/uploads/2010/08/template-before1.png"><img alt="Template before" class="alignleft size-full wp-image-230" height="85" src="http://www.scala-ide.org/wp-content/uploads/2010/08/template-before1.png" title="template-before" width="178"/></a></p>
<p>The resulting expansion:</p>
<p><a href="http://www.scala-ide.org/wp-content/uploads/2010/08/template-after1.png"><img alt="Template after" class="alignleft size-full wp-image-231" height="123" src="http://www.scala-ide.org/wp-content/uploads/2010/08/template-after1.png" title="template-after" width="267"/></a></p>
<h3>Quick Fix Imports</h3>
<p>More a bug fix than a new feature — <a href="http://www.colinhowe.co.uk/">Colin Howe</a> contributed this initially — <a href="http://scala-ide.assembla.com/profile/ratiud">Daniel Ratiu</a> has reinstated the quick fix which adds an import for a missing type.</p>
<p><a href="http://www.scala-ide.org/wp-content/uploads/2010/08/add-import-quick-fix1.png"><img alt="Add import quick fix" class="alignleft size-full wp-image-232" height="342" src="http://www.scala-ide.org/wp-content/uploads/2010/08/add-import-quick-fix1.png" title="add-import-quick-fix" width="590"/></a></p>
<h3>Structured Selections</h3>
<p>Matt has added support for Eclipse’s structured selection model — Alt-Shift-Up / Alt-Shift-Down select larger and smaller portions of the AST respectively:</p>
<p><a href="http://www.scala-ide.org/wp-content/uploads/2010/08/ast-select-11.png"><img alt="AST select 1" class="alignleft size-full wp-image-233" height="19" src="http://www.scala-ide.org/wp-content/uploads/2010/08/ast-select-11.png" title="ast-select-1" width="301"/></a><br/>
<a href="http://www.scala-ide.org/wp-content/uploads/2010/08/ast-select-21.png"><img alt="AST select 2" class="alignleft size-full wp-image-234" height="19" src="http://www.scala-ide.org/wp-content/uploads/2010/08/ast-select-21.png" title="ast-select-2" width="301"/></a><br/>
<a href="http://www.scala-ide.org/wp-content/uploads/2010/08/ast-select-31.png"><img alt="AST select 3" class="alignleft size-full wp-image-235" height="19" src="http://www.scala-ide.org/wp-content/uploads/2010/08/ast-select-31.png" title="ast-select-3" width="301"/></a><br/>
<a href="http://www.scala-ide.org/wp-content/uploads/2010/08/ast-select-41.png"><img alt="AST select 4" class="alignleft size-full wp-image-236" height="19" src="http://www.scala-ide.org/wp-content/uploads/2010/08/ast-select-41.png" title="ast-select-4" width="301"/></a></p>
<p>It works particularly nicely alongside the Extract Method and Extract Local refactorings mentioned above.</p>
<h3>XML Syntax Highlighting</h3>
<p>Matt has also carried on his work on Scala syntax highlighting thanks to which we now have full support for XML literals:</p>
<p><a href="http://www.scala-ide.org/wp-content/uploads/2010/08/xml-colouring1.png"><img alt="XML syntax highlighting" class="alignleft size-full wp-image-237" height="282" src="http://www.scala-ide.org/wp-content/uploads/2010/08/xml-colouring1.png" title="xml-colouring" width="397"/></a></p>
<p>As well as the highlighting of XML elements and attributes, you’ll see from the screenshot that Scala syntax (keywords, string literals etc.) which appear in XML content are now correctly left as unhighlighted text.</p>
<h3>Scala IDE support in m2eclipse</h3>
<p>To complement the use of Maven in the SDT’s own development process, we’re making rapid progress in ensuring that the Maven experience is as smooth as possible. In particular David Bernard has done sterling work on the <a href="http://scala-ide.assembla.com/wiki/show/scala-ide/With_M2Eclipse">m2eclipse Scala integration</a> started by Jason van Zyl with my encouragement at EclipseCon this year. </p>
<h4>An open platform with a growing community</h4>
<p/>
<p>Hopefully a few things are very evident from all of the above. One is that there’s a lively and growing community of active contributors around the project. Another is that the Scala IDE for Eclipse as an umbrella project is very much open to collaborations with projects which aren’t Eclipse-specific, or indeed tied to any kind of IDE at all — both Mirko’s refactoring tools and Matt’s formatter can be used from the command line or incorporated into other kinds of source manipulation tools.</p>
<p>So I’d like to finish by inviting you to join us — whether or not you’re an Eclipse user there is plenty the project as a whole has to offer, and plenty that you could contribute in return. Looking forward to seeing you on the <a href="http://groups.google.com/group/scala-ide-user">user</a> and <a href="http://groups.google.com/group/scala-ide-dev">developer</a> mailing lists!</p></div>
    </content>
    <updated>2010-08-12T09:59:09Z</updated>
    <published>2010-08-04T13:27:21Z</published>
    <category scheme="http://www.scala-ide.org" term="News"/>
    <category scheme="http://www.scala-ide.org" term="builds"/>
    <category scheme="http://www.scala-ide.org" term="formatting"/>
    <category scheme="http://www.scala-ide.org" term="refactoring"/>
    <category scheme="http://www.scala-ide.org" term="scala"/>
    <category scheme="http://www.scala-ide.org" term="templates"/>
    <author>
      <name>Miles Sabin</name>
      <uri>http://www.scala-ide.org</uri>
    </author>
    <source>
      <id>http://www.scala-ide.org/feed/atom/</id>
      <link href="http://www.scala-ide.org" rel="alternate" type="text/html"/>
      <link href="http://www.scala-ide.org/feed/atom/" rel="self" type="application/atom+xml"/>
      <title xml:lang="en">Scala IDE for Eclipse</title>
      <updated>2010-08-27T12:16:45Z</updated>
    </source>
  </entry>

  <entry xml:lang="en">
    <id>http://www.decodified.com/parboiled/2010/08/12/parboiled_0.9.8_released/</id>
    <link href="http://www.decodified.com/parboiled/2010/08/12/parboiled_0.9.8_released.html" rel="alternate" type="text/html"/>
    <title>parboiled 0.9.8 released</title>
    <summary type="xhtml"><div xmlns="http://www.w3.org/1999/xhtml"><p>Just about a month after the last release <em>parboiled</em> 0.9.8 has hit <a href="http://github.com/sirthias/parboiled/downloads">its github download page</a> today.<br/>It is once again a major step forward, with quite a few changes and additions, some of them being significant enough to accompany the release with a small series of blog posts. They should be of interest to both, people currently using previous <em>parboiled</em>...</p></div>
    </summary>
    <updated>2010-08-12T07:00:00Z</updated>
    <category scheme="http://www.decodified.com/categories/parboiled" term="parboiled"/>
    <source>
      <id>http://www.decodified.com</id>
      <author>
        <name>Mathias</name>
      </author>
      <link href="http://www.decodified.com" rel="alternate" type="text/html"/>
      <link href="http://feeds.feedburner.com/decodified" rel="self" type="application/rss+xml"/>
      <link href="http://pubsubhubbub.appspot.com/" rel="hub" type="text/html"/>
      <rights>Copyright 2010, decodified.com</rights>
      <subtitle>between code and cleartext</subtitle>
      <title>decodified</title>
      <updated>2010-09-03T09:16:29Z</updated>
    </source>
  </entry>
</feed>
