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

<channel>
	<title>Iulian Dragos</title>
	<atom:link href="http://www.iulidragos.org/?feed=rss2" rel="self" type="application/rss+xml" />
	<link>http://www.iulidragos.org</link>
	<description></description>
	<lastBuildDate>Sun, 23 Oct 2011 19:33:12 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.2</generator>
		<item>
		<title>Using a mirror for p2 repositories (with tycho)</title>
		<link>http://www.iulidragos.org/?p=207</link>
		<comments>http://www.iulidragos.org/?p=207#comments</comments>
		<pubDate>Thu, 22 Sep 2011 12:37:21 +0000</pubDate>
		<dc:creator>jaguarul</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://www.iulidragos.org/?p=207</guid>
		<description><![CDATA[It took me a while to figure this one out, so I'll write it down for future reference. We're using maven and tycho to manage builds for the Scala IDE. Our dependencies come both from maven and Eclipse P2 repositories, and http://download.eclipse.org is slow as molasses. Every build loses 4-5 seconds connecting to that repository [...]]]></description>
			<content:encoded><![CDATA[<p>It took me a while to figure this one out, so I'll write it down for future reference.</p>
<p>We're using maven and tycho to manage builds for the <a href="http://www.scala-ide.org">Scala IDE</a>. Our dependencies come both from maven and Eclipse P2 repositories, and <code>http://download.eclipse.org</code> is slow as molasses. Every build loses 4-5 seconds connecting to that repository (even when there's nothing to download). I finally made a local mirror (wget didn't work, so I had to use the <a href="http://wiki.eclipse.org/Equinox_p2_Repository_Mirroring">official way</a>).</p>
<p>The next step was to make this mirror available to my builds, without modifying the existing poms (it's an open source project, with contributors in several locations). Maven conveniently provides mirrors in a <a href="http://maven.apache.org/settings.html">per-user settings.xml</a> file, but for some reason P2 repositories didn't pick it up. It turns out you need to explicitly say it's a P2 repository (thanks to good people on this <a href="http://software.2206966.n2.nabble.com/P2-transparent-mirroring-td5793062.html">mail thread</a>):</p>
<p>[xml highlight_lines=12,13]<br />
  <mirrors><br />
    <!-- mirror<br />
     | Specifies a repository mirror site to use instead of a given repository. The repository that<br />
     | this mirror serves has an ID that matches the mirrorOf element of this mirror. IDs are used<br />
     | for inheritance and direct lookup purposes, and must be unique across the set of mirrors.<br />
     | --><br />
    <mirror><br />
      <id>local-helios</id><br />
      <mirrorOf>Helios</mirrorOf><br />
      <name>Local Mirror of Eclipse Helips p2 repository.</name><br />
      <url>http://iulians-imac.local/~dragos/mirrors/helios/</url><br />
      <layout>p2</layout><br />
      <mirrorOfLayouts>p2</mirrorOfLayouts><br />
    </mirror><br />
  </mirrors><br />
[/xml]</p>
]]></content:encoded>
			<wfw:commentRss>http://www.iulidragos.org/?feed=rss2&#038;p=207</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>How to use Java inner classes in Scala</title>
		<link>http://www.iulidragos.org/?p=166</link>
		<comments>http://www.iulidragos.org/?p=166#comments</comments>
		<pubDate>Tue, 07 Jun 2011 14:16:56 +0000</pubDate>
		<dc:creator>jaguarul</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[scala]]></category>

		<guid isPermaLink="false">http://www.iulidragos.org/?p=166</guid>
		<description><![CDATA[I just spent a wonderful week in California, and attended ScalaDays 2011. One thing that popped up during one of the talks was that 'Java inner classes in Scala are a challenge'. I was pretty surprised since this came from one of the speakers, and someone I'm sure is a very knowledgeable person otherwise. Of [...]]]></description>
			<content:encoded><![CDATA[<p>I just spent a wonderful week in California, and attended <a href="http://days2011.scala-lang.org/">ScalaDays 2011</a>. One thing that popped up during one of the talks was that 'Java inner classes in Scala are a challenge'. I was pretty surprised since this came from one of the speakers, and someone I'm sure is a very knowledgeable person otherwise. Of course, you can use Java inner classes in Scala. But first..</p>
<h2>Using Java inner classes in Java</h2>
<p>Let's call <em>nested</em> a class defined inside another class that is <em>static</em>, and let's call <em>inner class</em> a non-static class defined inside another class. Java uses the same syntax to refer to both nested and inner classes: <code>import Outer.Inner</code>. We'll consider the following example throughout this post:</p>
<p>[java gutter=false]<br />
package test;</p>
<p>public class Outer {<br />
    public int base = 10;<br />
    public class Inner {<br />
        public int x = 10 + base;<br />
    }<br />
}<br />
[/java]</p>
<p>You can use the Inner class either by subclassing <code>Outer</code>, or (less common), by importing and instantiating through an outer instance:</p>
<p>[java gutter=false highlight_lines=5]<br />
import test.Outer.Inner;<br />
import test.Outer;<br />
...<br />
Outer o = new Outer();<br />
Inner i = o.new Inner();<br />
i.x;<br />
[/java]</p>
<p>Java does not distinguish between instance and static members, so the import line looks unsurprising. However, the instantiation syntax is rather weird, making the keyword <code>new</code> look like a member of <code>o</code>, instead of making <code>Inner</code> look like a member of <code>o</code>. </p>
<blockquote><p>
An inner class has access to all members of the enclosing class, final and non-final alike. Therefore, whenever an inner class is instantiated it needs to be passed (implicitly) a reference to the outer instance.
</p></blockquote>
<h2>Inner classes in Scala</h2>
<p>Scala treats inner classes like any class members. Therefore, selection (both for importing and instantiation) proceeds with an outer value and goes on to select the inner type.</p>
<p>[Scala gutter=false]<br />
  val outer = new Outer<br />
  val inner = new outer.Inner<br />
[/Scala]</p>
<p>Note that due to type inference, there was no need to specify the type of <code>inner</code>. What is the type of <code>inner</code>?</p>
<p>[Scala gutter=false]<br />
  val outer = new Outer<br />
  val inner: outer.Inner = new outer.Inner<br />
[/Scala]</p>
<blockquote><p>We can use the same syntax to import the Inner type in scope: <code>import outer.Inner</code>.</p></blockquote>
<p>In Scala, types that depend on a value (the object <code>outer</code> in this example) are called <em>path-dependent types</em>. If we had a second instance of <code>Outer</code>, say <code>outer2</code>, the two types would be incompatible:</p>
<p>[Scala gutter=false]<br />
  val outer2 = new Outer<br />
  val inner2: outer.Inner = new outer2.Inner<br />
[/Scala]<br />
We'd get the following error:</p>
<pre>
outer.scala:7: error: type mismatch;
 found   : Test.outer2.Inner
 required: Test.outer.Inner
</pre>
<p>This is different behavior from Java, where type <code>Outer.Inner</code> matches any instance of <code>Inner</code>, regardless of the outer object instance. It turns out that Scala does have an equivalent type: <code>Outer#Inner</code>. The hash operator performs a <em>type selection</em>. Unlike Java, Scala reserves the dot exclusively for selection on terms.</p>
<p>[Scala gutter=false]<br />
  var inner: outer.Inner = new outer.Inner<br />
  var inner2: Outer#Inner = new outer2.Inner</p>
<p>  inner2 = inner // works<br />
  inner = inner2 // fails<br />
[/Scala]</p>
<h2>And the confusion?</h2>
<p>There is still one important difference between the way Scala and Java treat inner classes: mutability. Scala requires paths to be immutable, therefore both instantiation and imports have to mention only <code>vals</code>. The following code doesn't work:</p>
<p>[Scala gutter=false]<br />
  var outer = new Outer<br />
  val inner = new outer.Inner<br />
[/Scala]<br />
<code><br />
outer.scala:9: error: stable identifier required, but outer found.<br />
       var inner = new outer.Inner<br />
</code></p>
<blockquote><p>You may ask yourself why this restriction? It has to do with type members (remember, Scala classes may have abstract type members). If the path to the inner class contains mutable variables, the <em>type</em> of <code>Inner</code> members may change during execution. For example, a field may change from <code>Int</code> to <code>String</code>. In short, it's unsound.</p></blockquote>
<p>I believe it's this restriction that confuses most people. So what do you do if you need to have mutable outer instances? First of all, you need to use type selection (<code>Outer#Inner</code>) to refer to such types. Second, you need to instantiate them through an immutable alias, for instance by defining a helper method:<br />
[Scala gutter=false]<br />
  var outer1 = new Outer // outer1 is mutable, we need a factory method<br />
  val inner1 = mkInner(outer1)</p>
<p>  def mkInner(o: Outer): Outer#Inner = new o.Inner // o is immutable<br />
[/Scala]</p>
<blockquote><p>
The <code>Outer#Inner</code> syntax is not allowed in imports (it's not a <em>path</em>).</p></blockquote>
<p>With this observations, it should be always possible to use Java inner classes from Scala. I hope this post clarifies a (sometimes shady) part of the Java and Scala interoperability.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.iulidragos.org/?feed=rss2&#038;p=166</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>My new MacBook Pro (Early 2011) compiles Scala</title>
		<link>http://www.iulidragos.org/?p=159</link>
		<comments>http://www.iulidragos.org/?p=159#comments</comments>
		<pubDate>Thu, 19 May 2011 20:50:48 +0000</pubDate>
		<dc:creator>jaguarul</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[benchmark]]></category>

		<guid isPermaLink="false">http://www.iulidragos.org/?p=159</guid>
		<description><![CDATA[Yesterday I finally received my new Apple MacBook Pro, with the new SandyBridge core i7 processor. I was very eager to see how fast it is compared to my work computer (2010 iMac 27''), and what better benchmark than a full build of the Scala compiler? Here's the result (lower is better) The first benchmark [...]]]></description>
			<content:encoded><![CDATA[<p>Yesterday I finally received my new Apple MacBook Pro, with the new <a href="http://en.wikipedia.org/wiki/Sandybridge">SandyBridge </a>core i7 processor. I was very eager to see how fast it is compared to my work computer (2010 iMac 27''), and what better benchmark than a full build of the Scala compiler?</p>
<p>Here's the result (lower is better)</p>
<p><a href="http://www.iulidragos.org/wp-content/uploads/2011/05/sandy-scala-bench.png"><img src="http://www.iulidragos.org/wp-content/uploads/2011/05/sandy-scala-bench-300x211.png" alt="" title="Compile times for Scala (MBP early 2011, iMac 2010)" width="300" height="211" class="aligncenter size-medium wp-image-160" /></a></p>
<p>The first benchmark is the total time for a full build, the following are the bootstrapping steps of the Scala compiler and standard library. For the total time, the laptop is almost 1:30 minutes faster than the desktop!</p>
<p>Here are the two configurations (I ran both builds with a 2.5 GB heap, using Java 1.6/64 bits)</p>
<ul>
<li>MacBook Pro: 2.3 GHz quad-core i7 (sandy bridge) with Intel 320 SSD</li>
<li>iMac: 2.96 GHz quad-core i7 (first generation core i7)</li>
</ul>
<p>For sure the SSD on my MBP helps a lot, but the processor can't be bad either. I repeated the benchmark by having both computers write to a RAM-disk, and the results were very similar. Of course, the JDK, bootstrap compiler and sources were still on disk (HDD on the iMac, SSD on the laptop), so the laptop still has a signifficant advantage.</p>
<p>While this is certainly a flawed benchmark, and no general conclusions can be drawn, it is nevertheless something I do very often. It's great to see that my new laptop can deliver so well!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.iulidragos.org/?feed=rss2&#038;p=159</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Change Google Calendar Events.. in Scala</title>
		<link>http://www.iulidragos.org/?p=94</link>
		<comments>http://www.iulidragos.org/?p=94#comments</comments>
		<pubDate>Sun, 17 Apr 2011 10:33:28 +0000</pubDate>
		<dc:creator>jaguarul</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[GData]]></category>
		<category><![CDATA[scala]]></category>

		<guid isPermaLink="false">http://www.iulidragos.org/?p=94</guid>
		<description><![CDATA[It' been over 3 years since I finished my internship at Google, and lots of things happened in Scala-land since. A couple of days ago I went back to my code I wrote back then, and ported it to Scala 2.9.0.RC1. The project is a Scala client library for Google Data APIs. The GData Scala [...]]]></description>
			<content:encoded><![CDATA[<p>It' been over 3 years since I finished my internship at Google, and lots of things happened in Scala-land since. A couple of days ago I went back to my code I wrote back then, and ported it to Scala 2.9.0.RC1. The project is a <a href="http://code.google.com/p/gdata-scala-client/">Scala client library</a> for <a href="http://code.google.com/apis/gdata/">Google Data APIs</a>.</p>
<h2>The GData Scala Client Library</h2>
<p>Google Data (or GData) is an Atom-based publishing protocol that allows CRUD operations over Google services, such as Calendar, YouTube, GMail, etc. It is a very powerful mechanism that allows programatic access to all your Google-based thingies, but being XML-based it is very cumbersome to use directly. Google maintains a bunch of <em>client libraries</em> in different languages that hide all the ugly XML from programmers' eyes.</p>
<p>While at Google, I wrote a Scala client library, and I am still very pleased with the result. I strayed away from their Java client architecture, and for XML handling I wrote a <a href="http://research.microsoft.com/en-us/um/people/akenn/fun/picklercombinators.pdf">pickler library</a>. However, unlike the original paper that deals with sequential data, I had to make it work with XML trees, which proved a lot more interesting. Briefly, the library allows one to define bi-directional mapping between user types and XML using syntax that's reminiscent of Relax-NG schemas:</p>
<p>[Scala gutter=false]<br />
def pickler: Pickler[Rating] =<br />
    elem("rating",<br />
          opt(attr("average", doubleVal))<br />
        ~ attr("min", intVal)<br />
        ~ attr("max", intVal)<br />
        ~ opt(attr("numRaters", intVal))<br />
        ~ default(attr("rel", text), "overall")<br />
        ~ opt(attr("value", intVal)))(gdNs)<br />
[/Scala]</p>
<p>This code defines an element called 'rating' with an optional attribute average, of type Double, two required attributes of type int (min and max), an attribute with a default string value, and so on. This pickler defines two methods, one from XML to instances of Reminder, and another from Reminder to XML. The library provides type-safe, user-extensible picklers, meaning that the result of unpickling an XML element like</p>
<p>[xml gutter=false]<br />
<rating average="2.5" min="1" max="5"/><br />
[/xml]</p>
<p>will be an instance of the Rating class, and serializing an instance of Rating would generate conforming XML. One of the difficulties I faced was to allow permutation of child elements when parsing (the Atom protocol is very liberal in this regard, and Google servers use this liberty). I won't go further into the details of the implementation, as it is nicely described in the <a href="http://code.google.com/p/gdata-scala-client/wiki/DevelopersGuide">Developer's guide</a>.</p>
<p>The other part of the library deals with HTTP requests and binds together the XML serialization code with the network protocol.</p>
<h2>Updating birthday entries</h2>
<p>A couple of months ago I decided to organize my birthday calendar, and realized that most of the entries had a reminder, but some did not. This resulted in the suboptimal situation that I forgot some birthdays, but not all. I decided to fix this.. programmatically.</p>
<p>The code to do it in Scala is surprisingly simple:</p>
<p>[Scala gutter=false highlight_lines='27,32']<br />
package anivs</p>
<p>import com.google.gdata.calendar._<br />
import com.google.gdata.data.kinds.Reminder<br />
import Schemas._</p>
<p>object ChangeAnivs extends Application {<br />
  final val calName = "Birthdays"<br />
  val s = new CalendarService("test")<br />
  s.setUserCredentials("username@gmail.com", "secret")</p>
<p>  val cal = s.getOwnedUserCalendars.find(_.title.content.startsWith(calName)) match {<br />
	case Some(bcal) => bcal<br />
	case _ =><br />
	  println("couldn't find calendar")<br />
	  exit(1)<br />
  }<br />
  var link = cal.link(EVENT_FEED)</p>
<p>  while (link.isDefined) {<br />
    val events = s.getEvents(link.get.href)<br />
    println("* got back " + events.length + " events")<br />
    addReminders(events)<br />
    link = events.link("next")<br />
  }</p>
<p>  implicit def toOpt[T](s: T): Option[T] = Option(s)</p>
<p>  def addReminders(events: s.eventsFeed.Feed) {<br />
    for (event <- events if event.reminders.isEmpty) {<br />
      // alert 10 min before event<br />
      val rem = Reminder(method = "alert", minutes = 10)<br />
      event.reminders = List(rem)<br />
      val e1 = s.updateEvent(event)<br />
      println("Updated event " + e1.title.content)<br />
    }<br />
  }<br />
}<br />
[/Scala]</p>
<p>That's it! It adds a popup reminder to each event that has no reminders. Notice that the reminder uses <a href="http://www.scala-lang.org/node/2075">named parameters</a>, and the class has default values for most of its parameters (Atom has plenty of optional elements and attributes). I also added an implicit conversion from Any to Option, so that I don't need to wrap Some around the parameters I passed to Reminder.</p>
<h2>Next steps</h2>
<p>I plan a number of improvements to the code. <a href="http://code.google.com/p/gdata-scala-client/">GData-scala-client</a> was developed before <a href="http://code.google.com/p/simple-build-tool/">sbt</a> came to the scene, so I'd like to move the build from ant to sbt and publish it to the scala-tools.org maven repository. I already went through most GData-defined types and added default arguments and plan to more consistently use named parameters where possible. This should make the code much easier to understand. And lastly, I might add support for other services (currently, it supports Calendar, YouTube and Contacts) -- I'm a bit reluctant to say this too loud, though..</p>
]]></content:encoded>
			<wfw:commentRss>http://www.iulidragos.org/?feed=rss2&#038;p=94</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Imported some of my old posts</title>
		<link>http://www.iulidragos.org/?p=25</link>
		<comments>http://www.iulidragos.org/?p=25#comments</comments>
		<pubDate>Thu, 07 Apr 2011 21:28:39 +0000</pubDate>
		<dc:creator>jaguarul</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[WordPress]]></category>

		<guid isPermaLink="false">http://www.iulidragos.org/?p=25</guid>
		<description><![CDATA[I managed to import some of my old posts from b2evolution. There's no custom importer for WordPress, but the RSS importer worked like a charm: even formatting looks really good (it didn't import comments, but I didn't have that many anyway). However, the RSS feed had only the most recent 10 posts or so, meaning [...]]]></description>
			<content:encoded><![CDATA[<p>I managed to import some of my <a href="http://lampblogs.epfl.ch/b2evolution/blogs/index.php?blog=7">old posts</a> from b2evolution. There's no custom importer for WordPress, but the RSS importer worked like a charm: even formatting looks really good (it didn't import comments, but I didn't have that many anyway). However, the RSS feed had only the most recent 10 posts or so, <del>meaning I could not get about half of my posts</del>. Such is life.</p>
<p>(I could change the size of the RSS feed in b2evolution's settings).</p>
]]></content:encoded>
			<wfw:commentRss>http://www.iulidragos.org/?feed=rss2&#038;p=25</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>My new blog</title>
		<link>http://www.iulidragos.org/?p=11</link>
		<comments>http://www.iulidragos.org/?p=11#comments</comments>
		<pubDate>Thu, 07 Apr 2011 18:10:33 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[eclipse]]></category>
		<category><![CDATA[scala]]></category>

		<guid isPermaLink="false">http://www.iulidragos.org/?p=11</guid>
		<description><![CDATA[I finally decided to have a proper homepage, and blog from time to time. I may import some of my old blog posts, but until then I can leave you with my recent interview on jaxenter about the Scala IDE for Eclipse. &#160; My previous blog is here.]]></description>
			<content:encoded><![CDATA[<p>I finally decided to have a proper homepage, and blog from time to time. I may import some of my old blog posts, but until then I can leave you with my recent <a href="http://jaxenter.com/what-s-new-in-scala-ide-for-eclipse-2-0-branch-35559.html">interview on jaxenter</a> about the Scala IDE for Eclipse.</p>
<p>&nbsp;</p>
<p>My previous blog is <a href="https://lampblogs.epfl.ch/b2evolution/blogs/">here</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.iulidragos.org/?feed=rss2&#038;p=11</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Can we have Java-like asserts as library functions?</title>
		<link>http://www.iulidragos.org/?p=17</link>
		<comments>http://www.iulidragos.org/?p=17#comments</comments>
		<pubDate>Mon, 27 Aug 2007 12:56:42 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Scala compiler]]></category>

		<guid isPermaLink="false"></guid>
		<description><![CDATA[Here are my findings in trying to add Java-like asserts in Scala. In doing so, I tried to follow these lines: asserts should behave exactly like Java asserts they should not require any compiler changes (entirely done as library) they should be as efficient as in Java Java asserts Since Java 1.4, the assert keyword [...]]]></description>
			<content:encoded><![CDATA[<p>Here are my findings in trying to add <a href="http://java.sun.com/docs/books/jls/assert-spec.html">Java-like asserts</a> in Scala. In doing so, I tried to follow these lines:</p>
<ul>
<li>asserts should behave exactly like Java asserts</li>
<li>they should not require any compiler changes (entirely done as library)</li>
<li>they should be as efficient as in Java</li>
</ul>
<h2>Java asserts</h2>
<p>Since Java 1.4, the <code>assert</code> keyword has been added, allowing Java programs to have runtime checks. Assertions can be turned on or off "on-site", as a VM parameter, at the granularity of classes. The nice thing is that they incurr almost no cost at all when disabled: the condition and the optional error message are not evaluated unless assertions are enabled for the enclosing class. This suggests using call-by-name parameters to encode it in Scala. </p>
<h2>Scala asserts</h2>
<p>The VM hook to determine the assertion status is a new method in <code>java.lang.Class</code>, so here is a first attempt to code this in Scala (normally this method goes in <code>Predef</code>, but to keep samples simple I use another object):</p>
<pre>
<strong>object</strong> Prelude {
  <strong>def</strong> assert(prop: => Boolean, msg: => String): Unit = {
    <strong>if</strong> (this.getClass().desiredAssertionStatus() &amp;&amp; !prop)
      <strong>throw</strong> <strong>new</strong> AssertionError(msg)
  }
}
</pre>
<p>One problem is that the assertion status we get is wrong: it belongs to the <code>Prelude</code> object, instead of the caller's. We can add an implicit parameter to hold the <code>Class</code> of the caller. However, we don't want to have the user write any more code than in Java, so we need to add an implicit value in <code>ScalaObject</code> that is inherited by all Scala classes (for simplicity, we don't change ScalaObject, but create a new trait):</p>
<pre>
<strong>trait</strong> Assertable {
  implicit <strong>final</strong> <strong>val</strong> $cls = <strong>this</strong>.getClass()
}

<strong>object</strong> Prelude {
  <strong>def</strong> assert(prop: => Boolean, msg: => String)(implicit $cls: Class): Unit = {
    <strong>if</strong> ($cls.desiredAssertionStatus() &amp;&amp; !prop)
      <strong>throw</strong> <strong>new</strong> AssertionError(msg)
  }
}
</pre>
<p>We can test this code using:</p>
<pre>
<strong>object</strong> Foo <strong>extends</strong> Object <strong>with</strong> Assertable <strong>with</strong> Benchmark {
  <strong>val</strong> iters = 100000

  <strong>def</strong> run = {
    <strong>var</strong> i = 0
    <strong>while</strong> (i &lt; iters) {
      methodWithAssert(-1)
      i += 1
    }
  }

  <strong>def</strong> methodWithAssert(x: Int) {
    Prelude.assert(x > 0, <span class="str">"Negative x"</span>)
  }
}
</pre>
<p>Compiling with <code>-optimise</code> turns the above call to <code>Prelude.assert</code> into very much what <code>javac</code> outputs (like, no closure objects for the call-by-name parameters). The only difference is the call to <code>Class.desiredAssertionStatus</code>, which <code>javac</code> optimizes by storing its result in a final static field, initialized in the static initializer. Unfortunately, our code is 20-30 times slower than the Java version. It seems the native method is really expensive, and we'd better find a way to optimize this call. However, Scala does not have statics the way Java has, and we don't want to touch the compiler. The next best thing we can do is to make it an instance field. We can simply reuse the field used to hold the <code>java.lang.Class</code>:</p>
<pre>
<strong>trait</strong> Assertable {
  implicit <strong>final</strong> <strong>val</strong> $ea = <strong>this</strong>.getClass().desiredAssertionStatus()
}
</pre>
<p>Now the code is as fast as Java code!</p>
<p>Our solution costs one extra word per object, as opposed to one extra word per class in Java (in fact, javac won't generate such fields unless there is at least one call to <code>assert</code> in the enclosed class). This might be a worry... is it worth it? What we gain is less compiler magic, and show that we can extend the language with powerful libraries, without paying much in performance.</p>
<div class="item_footer">
<p><small><a href="http://lampblogs.epfl.ch/b2evolution/blogs/index.php/2007/08/27/can_we_have_java_like_asserts_as_library?blog=7">Original post</a> blogged on <a href="http://b2evolution.net/">b2evolution</a>.</small></p>
</div>
]]></content:encoded>
			<wfw:commentRss>http://www.iulidragos.org/?feed=rss2&#038;p=17</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Another use-case for lazy values</title>
		<link>http://www.iulidragos.org/?p=18</link>
		<comments>http://www.iulidragos.org/?p=18#comments</comments>
		<pubDate>Wed, 18 Jul 2007 16:22:58 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[lazy vals]]></category>
		<category><![CDATA[Scala compiler]]></category>

		<guid isPermaLink="false"></guid>
		<description><![CDATA[I found an interesting use case for lazy values while reading Don Syme's paper on initialization graphs: finite state automata (thanks to Philippe for the pointer). Curios to see how it would look in Scala, I implemented a simplified version of his example. trait Automaton { /** A type for signals. */ type Signal /** [...]]]></description>
			<content:encoded><![CDATA[<p>I found an interesting use case for lazy values while reading Don Syme's paper on <a href="http://research.microsoft.com/~dsyme/papers/valrec-tr.pdf">initialization graphs</a>: finite state automata (thanks to Philippe for the pointer). Curios to see how it would look in Scala, I implemented a simplified version of his example.</p>
<pre><code>
<strong>trait</strong> Automaton {
  <span class="cmt">/** A type for signals. */</span>
  <strong>type</strong> Signal

  <span class="cmt">/** The initial state. */</span>
  <strong>val</strong> initialState: State

  <strong>private</strong> <strong>var</strong> st: State = initialState
  <span class="cmt">/** The current state of this automaton. */</span>
  <strong>def</strong> state: State = st

  <strong>trait</strong> State {
    <strong>val</strong> name: String
    <strong>def</strong> react(sig: Signal): State
  }

  <strong>type</strong> Transitions = Map[Signal, () => State]

  <span class="cmt">/** React to the given symbol by making a transition. */</span>
  <strong>def</strong> react(sig: Signal) {
    st = state.react(sig)
  }

  <span class="cmt">/** An end state that makes no transitions. */</span>
  <strong>def</strong> finish(nme: String): State = <strong>new</strong> State {
    <strong>val</strong> name = nme
    <strong>def</strong> react(sig: Signal) = <strong>this</strong>
  }

  <span class="cmt">/** A state that can have multiple successors. */</span>
  <strong>def</strong> peekOne(nme: String, ts: Transitions) = <strong>new</strong> State {
    <strong>val</strong> name = nme
    <strong>def</strong> react(sig: Signal) =
      ts.get(sig) match {
        <strong>case</strong> Some(st) => st()
        <strong>case</strong> None => <strong>this</strong>
      }
  }
  implicit <strong>def</strong> stateToLazy(s: => State): () => State = () => s
}</code>
</pre>
<p>An automaton has an initial state, and can react to signals by changing state. States have a name and implement the react method to return the next state for a given input signal. Signals are fully abstract. We provide two methods for constructing states, <code>finish</code> creates a an end state, and <code>peekOne</code> which given a map from signals to states, returns a state that makes a transition according to this map. Ignore for the moment the fact that transitions take signals to <i>thunks</i> (functions that take unit and return a state).</p>
<p>Lazy values come in handy when one defines an automaton using this framework:</p>
<pre><code>
<strong>object</strong> Game <strong>extends</strong> Application {

  <strong>val</strong> game = <strong>new</strong> Automaton {
    <strong>type</strong> Signal = String

    lazy <strong>val</strong> initialState = start
    lazy <strong>val</strong> start: State = peekOne(<span class="str">"start"</span>,
                               immutable.Map((<span class="str">"run"</span>,   running),
                                             (<span class="str">"over"</span>,  over),
                                             (<span class="str">"reset"</span>, start)))
    lazy <strong>val</strong> over = finish(<span class="str">"over"</span>)
    lazy <strong>val</strong> running = peekOne(<span class="str">"running"</span>,
                               immutable.Map((<span class="str">"over"</span>,  over),
                                             (<span class="str">"reset"</span>, start),
                                             (<span class="str">"hit"</span>,   dead)))
    lazy <strong>val</strong> dead = peekOne(<span class="str">"dead"</span>,
                            immutable.Map((<span class="str">"reset"</span>, start),
                                          (<span class="str">"end"</span>,   over)))
    //...
  }
</code></pre>
<p>Defining the automaton in a natural way means some forward references of states, or recursive references, will exist. Without lazy values, the automaton would not be correctly initialized, as some states would be <code>null</code>. Of course, one could order the definitions according to the graph of dependencies, but this is cumbersome.</p>
<p>I get back now to the type of transitions, which uses delayed states:</p>
<pre><code>
  <strong>type</strong> Transitions = Map[Signal, () => State]
</code></pre>
<p>The reason is that a cycle in the automaton (like the one formed in state <code>start</code> with transition <code>reset</code>) would lead to an error, unless the recursive reference to the value being defined is <i>delayed</i>. This makes sense, since the value to the state being defined is not needed when constructing the state, but only when the automaton makes a transition. Scala provides a mechanism for such situations: <i>call-by-name</i> parameters. Unfortunately, they are an evaluation strategy, not a type, so we can't use them directly here: we can't define a <code>Map[Signal, => State]</code>. A <code>=></code> type may only appear in the parameter section of a definition, so we need an additional implicit conversion:</p>
<pre><code>
  implicit <strong>def</strong> stateToLazy(s: => State): () => State = () => s
</code></pre>
<p>This has the disadvantage that it creates two closures for each entry in the transition map, but the code looks much nicer. If this is too expensive, we can of course prepend <code>() =></code> to each reference to a state in the automaton definition, and change the type of transitions to <code>Map[Signal, State]</code>.</p>
<p>A few ideas:</p>
<ul>
<li>Could we extend call-by-name parameters to be real types, and therefore allowed everywhere a type is allowed? I see no real showstopper now. This would allow the definition of the transition type above, and save some closure classes.</li>
<li>Could we add a way to reference but not <i>dereference</i> lazy values? Right now this can be achieved by passing a lazy value to a call-by-name parameter, and then storing it back to a lazy value. Maybe a more traditional <i>delay</i>/<i>force</i> model of laziness makes  sense for Scala as well.</li>
</ul>
<div class="item_footer">
<p><small><a href="http://lampblogs.epfl.ch/b2evolution/blogs/index.php/2007/07/18/another_use_case_for_lazy_values?blog=7">Original post</a> blogged on <a href="http://b2evolution.net/">b2evolution</a>.</small></p>
</div>
]]></content:encoded>
			<wfw:commentRss>http://www.iulidragos.org/?feed=rss2&#038;p=18</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Aiguilles du Tour (romanian)</title>
		<link>http://www.iulidragos.org/?p=19</link>
		<comments>http://www.iulidragos.org/?p=19#comments</comments>
		<pubDate>Fri, 29 Jun 2007 15:39:04 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false"></guid>
		<description><![CDATA[My mountain blog has moved to blogspot. Original post blogged on b2evolution.]]></description>
			<content:encoded><![CDATA[<p>My mountain blog has moved to <a href="http://bloguluiuli.blogspot.com">blogspot</a>.</p>
<div class="item_footer">
<p><small><a href="http://lampblogs.epfl.ch/b2evolution/blogs/index.php/2007/06/29/aiguilles_du_tour_romanian?blog=7">Original post</a> blogged on <a href="http://b2evolution.net/">b2evolution</a>.</small></p>
</div>
]]></content:encoded>
			<wfw:commentRss>http://www.iulidragos.org/?feed=rss2&#038;p=19</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Adding continuations to the JVM</title>
		<link>http://www.iulidragos.org/?p=20</link>
		<comments>http://www.iulidragos.org/?p=20#comments</comments>
		<pubDate>Fri, 22 Jun 2007 20:50:30 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[continuations]]></category>
		<category><![CDATA[JVM]]></category>

		<guid isPermaLink="false"></guid>
		<description><![CDATA[My paper on adding continuations to the JVM was accepted in the ICOOOLPS workshop at Ecoop 2007. You can have a look at it here. You can try the thing by downloading the the modified Ovm and the examples. Original post blogged on b2evolution.]]></description>
			<content:encoded><![CDATA[<p>My paper on adding continuations to the JVM was accepted in the <a href="http://icooolps.loria.fr/">ICOOOLPS</a> workshop at <a href="http://ecoop07.swt.cs.tu-berlin.de/">Ecoop 2007</a>. You can have a look at it <a href="http://lamp.epfl.ch/~dragos/files/ecoop-workshop.pdf">here</a>.</p>
<p>You can try the thing by downloading the the <a href="http://lamp.epfl.ch/~dragos/files/ovm-cont.zip">modified Ovm</a> and the <a href="http://lamp.epfl.ch/~dragos/files/ovm-cont-examples.zip">examples</a>.</p>
<div class="item_footer">
<p><small><a href="http://lampblogs.epfl.ch/b2evolution/blogs/index.php/2007/06/22/adding_continuations_to_the_jvm?blog=7">Original post</a> blogged on <a href="http://b2evolution.net/">b2evolution</a>.</small></p>
</div>
]]></content:encoded>
			<wfw:commentRss>http://www.iulidragos.org/?feed=rss2&#038;p=20</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

