<?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/"
	xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>Michid's Weblog</title>
	<atom:link href="http://michid.wordpress.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://michid.wordpress.com</link>
	<description>Hacking Scala</description>
	<lastBuildDate>Mon, 31 Aug 2009 08:27:46 +0000</lastBuildDate>
	<generator>http://wordpress.com/</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<cloud domain='michid.wordpress.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://www.gravatar.com/blavatar/8a44e33f0c0b6ba0377f3633082fb84d?s=96&#038;d=http://s.wordpress.com/i/buttonw-com.png</url>
		<title>Michid's Weblog</title>
		<link>http://michid.wordpress.com</link>
	</image>
			<item>
		<title>Implementing Java Interfaces and Generics</title>
		<link>http://michid.wordpress.com/2009/08/30/implementing-java-interfaces-and-generics/</link>
		<comments>http://michid.wordpress.com/2009/08/30/implementing-java-interfaces-and-generics/#comments</comments>
		<pubDate>Sun, 30 Aug 2009 19:20:42 +0000</pubDate>
		<dc:creator>michid</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Scala]]></category>

		<guid isPermaLink="false">http://michid.wordpress.com/?p=163</guid>
		<description><![CDATA[In an earlier post I asked for an implementation of the following Java interface in Scala:

public interface Iterator2 extends java.util.Iterator {}

The solution was to use a combination of self types and existential types. However, some comments made me aware of Ticket #1737 where a more general form of the problem is discussed. Given the following [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=michid.wordpress.com&blog=2538862&post=163&subd=michid&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>In an earlier <a href="http://michid.wordpress.com/2009/06/19/puzzle-implement-this/">post</a> I asked for an implementation of the following Java interface in Scala:</p>
<pre class="brush: java;">
public interface Iterator2 extends java.util.Iterator {}
</pre>
<p>The <a href="http://michid.wordpress.com/2009/06/24/puzzle-implement-this-solution/">solution</a> was to use a combination of self types and existential types. However, some comments made me aware of <a href="http://lampsvn.epfl.ch/trac/scala/ticket/1737">Ticket #1737</a> where a more general form of the problem is discussed. Given the following Java code:</p>
<pre class="brush: java;">
public interface A&lt;T&gt; {
    void run(T t);
    T get();
}

public abstract class B implements A {}
</pre>
<p>How could <em>B</em> be implemented in Scala? My previous approach is not sufficient here since for implementing the <em>run()</em> method, one needs to be able to refer to the existential type in <em>run()</em>&#8217;s parameter list: </p>
<pre class="brush: java;">
class C extends B {
  this: A[_] =&gt;

  def run(t:???) {} // What should go here for t's type?
  def get = &quot;hello world&quot;
}
</pre>
<p>So what we need is a way to name the existential type used in the self type (that is the type parameter to <em>A</em>) such that we can refer to it in the parameter list of the <em>run()</em> method. Here is my shot:</p>
<pre class="brush: java;">
class D {
  type Q = X forSome { type X; }
}

class C extends B {
  this: A[D#Q] =&gt;

  def run(t:D#Q ) {}
  def get: D#Q = &quot;hello world&quot;
}
</pre>
<p>Unfortunately this results in a compilation error with Scala 2.7.5</p>
<pre>
error: class C needs to be abstract, since method run in trait A of type (T)Unit is not defined
</pre>
<p>and in a <em>AssertionError</em> for Scala  2.8.0.r18604-b20090830020201</p>
<pre>
Exception in thread "main" java.lang.AssertionError: assertion failed: michid.iterator.A[T]
at scala.Predef$.assert(Predef.scala:107)
at scala.tools.nsc.symtab.Types$TypeRef.transform(Types.scala:1417)
at scala.tools.nsc.symtab.Types$TypeRef$$anonfun$baseTypeSeq$3.apply(Types.scala:1588)
...
</pre>
<p>I created <a href="http://lampsvn.epfl.ch/trac/scala/ticket/2091">Ticket #2091</a> for these problems. </p>
Posted in Uncategorized Tagged: Scala <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/michid.wordpress.com/163/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/michid.wordpress.com/163/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/michid.wordpress.com/163/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/michid.wordpress.com/163/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/michid.wordpress.com/163/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/michid.wordpress.com/163/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/michid.wordpress.com/163/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/michid.wordpress.com/163/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/michid.wordpress.com/163/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/michid.wordpress.com/163/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=michid.wordpress.com&blog=2538862&post=163&subd=michid&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://michid.wordpress.com/2009/08/30/implementing-java-interfaces-and-generics/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="" medium="image">
			<media:title type="html">michid</media:title>
		</media:content>
	</item>
		<item>
		<title>Scala for Sling @ Jazzon 09</title>
		<link>http://michid.wordpress.com/2009/06/26/scala-for-sling-jazzon-09/</link>
		<comments>http://michid.wordpress.com/2009/06/26/scala-for-sling-jazzon-09/#comments</comments>
		<pubDate>Fri, 26 Jun 2009 13:38:06 +0000</pubDate>
		<dc:creator>michid</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[JCR]]></category>
		<category><![CDATA[Scala]]></category>
		<category><![CDATA[Sling]]></category>

		<guid isPermaLink="false">http://michid.wordpress.com/?p=156</guid>
		<description><![CDATA[Yesterday I gave a presentation at Jazoon 09 about using Scala for scripting RESTful web applications with Apache Sling. 
In the session I showed how to take advantage of Scala to create RESTful web applications with Apache Sling. I demonstrated how to uses its DSL capability and support for XML literals to create type safe [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=michid.wordpress.com&blog=2538862&post=156&subd=michid&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>Yesterday I gave a <a href="http://jazoon.com/en/conference/presentationdetails.html?type=sid&amp;detail=10080">presentation</a> at <a href="http://jazoon.com/">Jazoon 09</a> about using <a href="http://www.scala-lang.org">Scala</a> for scripting <a href="http://www.ics.uci.edu/~fielding/pubs/dissertation/top.htm">RESTful</a> web applications with <a href="http://incubator.apache.org/sling/">Apache Sling</a>. </p>
<p>In the session I showed how to take advantage of Scala to create RESTful web applications with Apache Sling. I demonstrated how to uses its DSL capability and support for XML literals to create type safe web site templates. In contrast to conventional web site template mechanisms (e.g. JSP), this does not rely on a  pre-processor but rather uses pure Scala code. </p>
<p>There are <a href="http://people.apache.org/~mduerig/scala4sling/scala4sling.pdf">Session slides</a> and <a href="http://people.apache.org/~mduerig/scala4sling/scala4sling-demo.zip">support material</a> available <a href="http://people.apache.org/~mduerig/scala4sling/">here</a>. The support material contains a fully workable demo application. A Scala scripting bundle for Sling is also included. </p>
Posted in Uncategorized Tagged: JCR, Scala, Sling <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/michid.wordpress.com/156/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/michid.wordpress.com/156/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/michid.wordpress.com/156/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/michid.wordpress.com/156/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/michid.wordpress.com/156/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/michid.wordpress.com/156/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/michid.wordpress.com/156/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/michid.wordpress.com/156/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/michid.wordpress.com/156/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/michid.wordpress.com/156/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=michid.wordpress.com&blog=2538862&post=156&subd=michid&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://michid.wordpress.com/2009/06/26/scala-for-sling-jazzon-09/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="" medium="image">
			<media:title type="html">michid</media:title>
		</media:content>
	</item>
		<item>
		<title>Puzzle: implement this (solution)</title>
		<link>http://michid.wordpress.com/2009/06/24/puzzle-implement-this-solution/</link>
		<comments>http://michid.wordpress.com/2009/06/24/puzzle-implement-this-solution/#comments</comments>
		<pubDate>Wed, 24 Jun 2009 20:51:35 +0000</pubDate>
		<dc:creator>michid</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Puzzle]]></category>
		<category><![CDATA[Scala]]></category>

		<guid isPermaLink="false">http://michid.wordpress.com/?p=151</guid>
		<description><![CDATA[Well, I wasn&#8217;t aware of Ticket #1737 when I was trying to find a solution to the problem from my previous post. Thanks to Jorge Ortiz for pointing this out. However, I reviewed my approach to solving this and didn&#8217;t find sever limitations. Maybe someone else does&#8230;
When I initially stumbled on this, I remembered that [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=michid.wordpress.com&blog=2538862&post=151&subd=michid&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>Well, I wasn&#8217;t aware of <a href="http://lampsvn.epfl.ch/trac/scala/ticket/1737">Ticket #1737</a> when I was trying to find a solution to the problem from my <a href="http://michid.wordpress.com/2009/06/19/puzzle-implement-this/">previous post</a>. Thanks to <a href="http://michid.wordpress.com/2009/06/19/puzzle-implement-this/#comment-283">Jorge Ortiz</a> for pointing this out. However, I reviewed my approach to solving this and didn&#8217;t find sever limitations. Maybe someone else does&#8230;</p>
<p>When I initially stumbled on this, I remembered that existential types where introduced into Scala for coping with Java&#8217;s raw types. But there is an additional twist here, we need to tell the compiler that our <em>MyIterator</em> implementation actually &#8216;is an instance of a raw type&#8217;. So combining existential types with self types led me to the following solution:</p>
<pre class="brush: java;">
class MyIterator extends Iterator2 {
  this: java.util.Iterator[_] =&gt;
  def hasNext = true
  def remove = throw new Error
  def next = &quot;infinity&quot;
}
</pre>
<p>We can now safely use instances of <em>MyIterator</em>. </p>
<pre class="brush: java;">
  def test1(it: MyIterator) = {
    println(it.next)
  }

  def test2(it: java.util.Iterator[_]) = {
    println(it.next)
  }

  val it = new MyIterator
  val v: String = it.next
  println(v)

  test1(it)
  test2(it)
</pre>
<p>The approach using existential types in combination with self types makes sure that values returned from the <em>next</em> method always are typed correctly.</p>
Posted in Uncategorized Tagged: Puzzle, Scala <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/michid.wordpress.com/151/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/michid.wordpress.com/151/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/michid.wordpress.com/151/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/michid.wordpress.com/151/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/michid.wordpress.com/151/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/michid.wordpress.com/151/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/michid.wordpress.com/151/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/michid.wordpress.com/151/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/michid.wordpress.com/151/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/michid.wordpress.com/151/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=michid.wordpress.com&blog=2538862&post=151&subd=michid&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://michid.wordpress.com/2009/06/24/puzzle-implement-this-solution/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="" medium="image">
			<media:title type="html">michid</media:title>
		</media:content>
	</item>
		<item>
		<title>Puzzle: implement this</title>
		<link>http://michid.wordpress.com/2009/06/19/puzzle-implement-this/</link>
		<comments>http://michid.wordpress.com/2009/06/19/puzzle-implement-this/#comments</comments>
		<pubDate>Fri, 19 Jun 2009 20:28:42 +0000</pubDate>
		<dc:creator>michid</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[JCR]]></category>
		<category><![CDATA[Puzzle]]></category>
		<category><![CDATA[Scala]]></category>

		<guid isPermaLink="false">http://michid.wordpress.com/?p=135</guid>
		<description><![CDATA[This is something I stumbled on recently when trying to implement javax.jcr.NodeIterator in Scala.
Assume you are using a library which exports an Iterator2 interface:

public interface Iterator2 extends java.util.Iterator {}

Note that Iterator is a raw type and Iterator2 does not take any type parameters. So how would you implement Iterator2 in Scala?
Here is a start: 

class [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=michid.wordpress.com&blog=2538862&post=135&subd=michid&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>This is something I stumbled on recently when trying to implement <a href="http://www.day.com/maven/jsr170/javadocs/jcr-1.0/javax/jcr/NodeIterator.html">javax.jcr.NodeIterator</a> in <a>Scala.</a></p>
<p>Assume you are using a library which exports an <em>Iterator2</em> interface:</p>
<pre class="brush: java;">
public interface Iterator2 extends java.util.Iterator {}
</pre>
<p>Note that <em>Iterator</em> is a raw type and <em>Iterator2</em> does not take any type parameters. So how would you implement <em>Iterator2</em> in Scala?</p>
<p>Here is a start: </p>
<pre class="brush: java;">
class MyIterator extends Iterator2 {
  def hasNext = false
  def remove = throw new Error
  def next: Nothing = throw new Error
}
</pre>
<p>But if the <em>next</em> method should return an actual value, what would be it&#8217;s return type? It turn&#8217;s out that any other type than <em>Nothing</em> results in a compiler error:</p>
<pre>
error overriding method next in trait Iterator of type ()E;
method next has incompatible type ()Any
</pre>
<p>So how would you implement <em>Iterator2</em>? </p>
Posted in Uncategorized Tagged: JCR, Puzzle, Scala <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/michid.wordpress.com/135/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/michid.wordpress.com/135/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/michid.wordpress.com/135/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/michid.wordpress.com/135/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/michid.wordpress.com/135/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/michid.wordpress.com/135/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/michid.wordpress.com/135/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/michid.wordpress.com/135/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/michid.wordpress.com/135/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/michid.wordpress.com/135/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=michid.wordpress.com&blog=2538862&post=135&subd=michid&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://michid.wordpress.com/2009/06/19/puzzle-implement-this/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
	
		<media:content url="" medium="image">
			<media:title type="html">michid</media:title>
		</media:content>
	</item>
		<item>
		<title>Function Memoization in Scala</title>
		<link>http://michid.wordpress.com/2009/02/23/function_mem/</link>
		<comments>http://michid.wordpress.com/2009/02/23/function_mem/#comments</comments>
		<pubDate>Mon, 23 Feb 2009 20:30:37 +0000</pubDate>
		<dc:creator>michid</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://michid.wordpress.com/?p=119</guid>
		<description><![CDATA[Function memoization is an optimization technique to avoid repeated calculation of function values which have been calculated by a previous evaluation of the function. In this post I show how function memoization can be implemented in Scala. Although straight forward at a first glance, effectively memoizing recursive functions requires some second thoughts. For the sake [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=michid.wordpress.com&blog=2538862&post=119&subd=michid&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>Function <a href="http://en.wikipedia.org/wiki/Memoization">memoization</a> is an optimization technique to avoid repeated calculation of function values which have been calculated by a previous evaluation of the function. In this post I show how function memoization can be implemented in <a href="http://scala-lang.org/">Scala</a>. Although straight forward at a first glance, effectively memoizing recursive functions requires some second thoughts. For the sake of simplicity I only discuss functions of arity one. </p>
<p>Assume we have a function <em>strSqLen</em> which calculates the square of the length of a string. </p>
<pre class="brush: java;">
def strSqLen(s: String) = s.length*s.length
</pre>
<p>Assume further, that for some reason evaluating above function is processor intensive. One way to speed things up is to cache result values and to look them up on subsequent invocations of <em>strSqLen</em>. This can be done either by the function itself or by the caller. The first approach has the drawback that each and every function has to implement caching and that clients have no control over the caching mechanism. The latter approach puts all the burden on the client programmer and produces potential boilerplate. To overcome these issues we need a way to construct a memoized function having the same type as a given function. </p>
<p>In Scala a function of arity one is an instance of <a href="http://www.scala-lang.org/docu/files/api/scala/Function1.html"><em>Function1</em></a>. We can thus sub-class a <em>Function[-T, +R]</em> to <em>Memoize1[-T, +R]</em> which represents the memoized function. (Note the concise syntactic sugar <em>T =&gt; R</em> which is synonym to the more verbose <em>Function1[T, R]</em>.)</p>
<pre class="brush: java;">
class Memoize1[-T, +R](f: T =&gt; R) extends (T =&gt; R) {
  import scala.collection.mutable
  private[this] val vals = mutable.Map.empty[T, R]

  def apply(x: T): R = {
    if (vals.contains(x)) {
      vals(x)
    }
    else {
      val y = f(x)
      vals + ((x, y))
      y
    }
  }
}

object Memoize1 {
  def apply[T, R](f: T =&gt; R) = new Memoize1(f)
}
</pre>
<p>When applied to an argument of type <em>T</em>, <em>apply</em> checks whether the function value is in the cache. If so, it returns that value. If not, it calls the original function <em>f</em>, puts the function value into the cache and returns it. Note that the member <em>vals</em> which contains the cached function values has <a href="http://www.scala-lang.org/docu/files/ScalaReference.pdf">object private</a> visibility (<em>private[this]</em>). A less restrictive visibility would cause type checking to fail since <a href="http://www.scala-lang.org/docu/files/api/scala/collection/mutable/Map.html"><em>mutable.Map[A, B]</em></a> is invariant in both its type arguments while <em>Memoize1[-T, +R]</em> is contravariant in <em>T</em> and covariant in <em>R</em> (as is <em>Function1[-T, +R]</em>). However since <em>vals</em> is accessed from its containing instance only, it cannot cause problems with variance. We tell this to the compiler by declaring the field object private.</p>
<p>We can now easily create and use a memoization of <em>strSqLen</em> like this:</p>
<pre class="brush: java;">
val strSqLenMemoized = Memoize1(strSqLen)
val a = strSqLenMemoized(&quot;hello Memo&quot;)
val b = strSqLen(&quot;hello Memo&quot;)
assert(a == b)
</pre>
<h3>Going recursive</h3>
<p>Memoization of recursive functions is possible but might not expose the desired effect. Consider the following recursive implementation of the factorial function.</p>
<pre class="brush: java;">
def fac(n: BigInt): BigInt = {
  if (n == 0) 1
  else n*fac(n - 1)
}
</pre>
<p>Calculating the factorials from 200 down to 0 does not take advantage of the memoization at all.</p>
<pre class="brush: java;">
val facMem = Memoize1(fac)

for (k &lt;- 200 to 0 by -1) {
  println(facMem(k))
}
</pre>
<p>While <em>facMem(200)</em> caches the factorial of 200, it does not cache the results of its intermediate recursive invocations since the recursive calls invoke the original function instead of the memoized. When it comes to calculating <em>facMem(199)</em> there is no gain from memoization here since &#8211; although calculated before &#8211; <em>facMem(199)</em> is not cached.</p>
<p>To improve this we need a more flexible implementation of <em>fac</em>. We want its recursive calls to be available on the outside such that they are available for caching. </p>
<pre class="brush: java;">
def facRec(n: BigInt, f: BigInt =&gt; BigInt): BigInt = {
  if (n == 0) 1
  else n*f(n - 1)
}
</pre>
<p>Here the caller needs to pass a function for calculating factorials to <em>factRec</em>. She is therefore free to pass a memoized function to speed up recurrent invocations. However, it seems we are back to square one: we need to pass a function for calculating factorials do <em>facRec</em> in order for it to calculate factorials. As it turns out this is not the case. By passing <em>facRec</em> to itself recursively, we can construct the desired factorial function.</p>
<pre class="brush: java;">
var fac: BigInt =&gt; BigInt = null
fac = facRec(_, fac(_))
</pre>
<p>First we declare function <em>fac</em> to map from <em>BigInt</em> to <em>BigInt</em>. Then we partially apply <em>facRec</em> to <em>fac</em> which yields the desired factorial function. </p>
<p>We can generalize and factor out this construction process into an object <a href="http://en.wikipedia.org/wiki/Y_combinator"><em>Y</em></a> like this:</p>
<pre class="brush: java;">
object Y {
  def apply[T, R](f: (T, T =&gt; R) =&gt; R): (T =&gt; R) = {
    var yf: T =&gt; R = null
    yf = f(_, yf(_))
    yf
  }
}
</pre>
<p>Along the same lines we can provide functionality for creating memoized versions of recursive functions. Instead of just recursively invoking the passed function, we pass a memoized version of it.</p>
<pre class="brush: java;">
object Memoize1 {
  // ... same as above

  def Y[T, R](f: (T, T =&gt; R) =&gt; R) = {
    var yf: T =&gt; R = null
    yf = Memoize1(f(_, yf(_)))
    yf
  }
}
</pre>
<p>Using <em>Memoize1.Y</em> we can calculate the factorials from 200 down to 0 while taking full advantage of memoization of all intermediate recursive invocation.</p>
<pre class="brush: java;">
def facRec(n: BigInt, f: BigInt =&gt; BigInt): BigInt = {
  if (n == 0) 1
  else n*f(n - 1)
}

val fac = Memoize1.Y(facRec)

for (k &amp;lt;- 200 to 0 by -1)
  println(fac(k))
</pre>
Posted in Uncategorized  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/michid.wordpress.com/119/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/michid.wordpress.com/119/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/michid.wordpress.com/119/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/michid.wordpress.com/119/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/michid.wordpress.com/119/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/michid.wordpress.com/119/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/michid.wordpress.com/119/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/michid.wordpress.com/119/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/michid.wordpress.com/119/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/michid.wordpress.com/119/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=michid.wordpress.com&blog=2538862&post=119&subd=michid&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://michid.wordpress.com/2009/02/23/function_mem/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
	
		<media:content url="" medium="image">
			<media:title type="html">michid</media:title>
		</media:content>
	</item>
		<item>
		<title>Meta-Programming with Scala: Conditional Compilation and Loop Unrolling</title>
		<link>http://michid.wordpress.com/2008/10/29/meta-programming-with-scala-conditional-compilation-and-loop-unrolling/</link>
		<comments>http://michid.wordpress.com/2008/10/29/meta-programming-with-scala-conditional-compilation-and-loop-unrolling/#comments</comments>
		<pubDate>Wed, 29 Oct 2008 23:38:56 +0000</pubDate>
		<dc:creator>michid</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Meta-Programming]]></category>
		<category><![CDATA[Scala]]></category>

		<guid isPermaLink="false">http://michid.wordpress.com/?p=89</guid>
		<description><![CDATA[The kind of comments I keep getting on my static meta-programming with Scala blogs are often along the lines of: &#8220;The ability to encode Church Numerals in Scala still seems uselessly academic to me, but cool none-the-less&#8221;. In this blog I will show how meta-programming can be applied in practice &#8211; at least theoretically.
In my [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=michid.wordpress.com&blog=2538862&post=89&subd=michid&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>The kind of comments I keep getting on my <a href="http://michid.wordpress.com/2008/04/18/meta-programming-with-scala-part-i-addition/">static</a> <a href="http://michid.wordpress.com/2008/07/30/meta-programming-with-scala-part-ii-multiplication/">meta-programming</a> with <a href="http://michid.wordpress.com/2008/08/27/meta-programming-with-scala-part-iii-partial-function-application/">Scala</a> blogs are often <a href="http://michid.wordpress.com/2008/07/30/meta-programming-with-scala-part-ii-multiplication/#comment-67">along the lines</a> of: &#8220;The ability to encode Church Numerals in Scala still seems uselessly academic to me, but cool none-the-less&#8221;. In this blog I will show how meta-programming can be applied in practice &#8211; at least theoretically.</p>
<p>In my previous  blogs I introduced a technique for static meta-programing with Scala. This technique uses Scala&#8217;s type system to encode values and functions on these values. The Scala compiler acts as interpreter of such functions. That is, the type checking phase of the Scala compiler actually carries out calculations like <a href="http://michid.wordpress.com/2008/04/18/meta-programming-with-scala-part-i-addition/">addition</a> and <a href="http://michid.wordpress.com/2008/08/27/meta-programming-with-scala-part-iii-partial-function-application/">multiplication</a>. </p>
<p>In this post I show how to apply meta-programming for two practical problems: conditional compilation and loop unrolling. The examples make use of type level encoding for booleans and natural numbers. While I introduced an encoding for natural numbers before, I use an alternative method which is more powerful in this post. Previously it was not possible to build nested expressions having expressions as operands themselves. The new encoding supports such expressions. However, in general the new encoding depends on the <a href="http://lampsvn.epfl.ch/trac/scala/changeset/16035/scala/trunk/src/compiler">-Yrecursion</a> compiler flag which is experimental and as of now only available in the Scala trunk. The type level encoding for booleans is along the same lines as the one for natural numbers. </p>
<h3>Conditional Compilation</h3>
<p>Conditional compilation is useful for example for enabling or disabling debugging or logging statements. Ideally code which is excluded by a compile time condition does not have any effect on the run-time behavior of the rest of the code. That is, the rest of the code behaves exactly as if the excluded code were not there at all. Optimizing compilers generally remove  code which is unreachable. This is where meta-programming fits in: type level encoded functions (meta-functions) are evaluated at run-time. The result of the evaluation is a type. Now we only need to trick the compiler into compiling a block of code or not compiling it depending on that type. </p>
<p>Lets first define meta-booleans and some operations on them (<a href="http://michid.wordpress.com/code/meta-programming-with-scala-conditional-compilation/">full code here</a>):</p>
<pre class="brush: java;">
object Booleans {
  trait BOOL {
    type a[t &lt;: BOOL, f &lt;: BOOL] &lt;: BOOL
    type v = a[TRUE, FALSE]
  }
  final class TRUE extends BOOL {
    type a[t &lt;: BOOL, f &lt;: BOOL] = t
  }
  final class FALSE extends BOOL{
    type a[t &lt;: BOOL, f &lt;: BOOL] = f
  }
  trait IF[x &lt;: BOOL, y &lt;: BOOL, z &lt;: BOOL] extends BOOL {
    type a[t &lt;: BOOL, f &lt;: BOOL] = x#a[y, z]#a[t, f]
  }
  trait NOT[x &lt;: BOOL] extends BOOL {
    type a[t &lt;: BOOL, f &lt;: BOOL] = IF[x, FALSE, TRUE]#a[t, f]
  }
  trait AND[x &lt;: BOOL, y &lt;: BOOL] extends BOOL {
    type a[t &lt;: BOOL, f &lt;: BOOL] = IF[x, y, FALSE]#a[t, f]
  }
  trait OR[x &lt;: BOOL, y &lt;: BOOL] extends BOOL {
    type a[t &lt;: BOOL, f &lt;: BOOL] = IF[x, TRUE, y]#a[t, f]
  }

  // aliases for nicer syntax
  type ![x &lt;: BOOL] = NOT[x]
  type ||[x &lt;: BOOL, y &lt;: BOOL] = OR[x, y]
  type &amp;&amp;[x &lt;: BOOL, y &lt;: BOOL] = AND[x, y]
}
</pre>
<p>The following pre-processor object contains an <a href="http://www.scala-lang.org/node/114">implicit</a> method for converting a value of type <em>TRUE</em> to an <em>Include</em> object whose <em>apply</em> method executes a block of code. Similarly it contains an implicit method for converting a value of type <em>FALSE</em> to an <em>Exclude</em> object whose <em>apply</em> method simply does nothing. The strange line where <em>null</em> is being cast to <em>B</em> is a trick for getting a witnesses of a value of type <em>B</em>.</p>
<pre class="brush: java;">
object PreProc {
  def IF[B] = null.asInstanceOf[B]

  object Include {
    def apply(block: =&gt; Unit) {
      block
    }
  }

  object Exclude {
    def apply(block: =&gt; Unit) { }
  }

  implicit def include(t: TRUE) = Include
  implicit def exclude(f: FALSE) = Exclude
}
</pre>
<p>Using these definitions is quite convenient now: </p>
<pre class="brush: java;">
object IfDefTest {
  import PreProc._

  type LOG = TRUE
  type ERR = TRUE
  type WARN = FALSE

  def errTest() {
    IF[(LOG &amp;&amp; ERR)#v] {
      println(&quot;err&quot;)
    }
  }

  def warnTest() {
    IF[(LOG &amp;&amp; WARN)#v] {
      println(&quot;warn&quot;)
    }
  }

  def main(args: Array[String]) {
    errTest()
    warnTest()
  }
}
</pre>
<p>Running the above code will print <em>err</em> but wont print <em>warn</em> to the console. </p>
<h3>Loop Unrolling</h3>
<p>Another application for static meta-programming is loop unrolling. When the number of iterations of a loop is small and only depends on quantities known at compile time, run time performance might profit from unrolling that loop. Instead of resorting to copy paste, we can use similar techniques like above.</p>
<p>Again let&#8217;s first define meta-naturals and their operations (<a href="http://michid.wordpress.com/code/meta-programming-with-scala-loop-unrolling/">full code here</a>):</p>
<pre class="brush: java;">
object Naturals {
  trait NAT {
    type a[s[_ &lt;: NAT] &lt;: NAT, z &lt;: NAT] &lt;: NAT
    type v = a[SUCC, ZERO]
  }
  final class ZERO extends NAT {
    type a[s[_ &lt;: NAT] &lt;: NAT, z &lt;: NAT] = z
  }
  final class SUCC[n &lt;: NAT] extends NAT {
    type a[s[_ &lt;: NAT] &lt;: NAT, z &lt;: NAT] = s[n#a[s, z]]
  }
  type _0 = ZERO
  type _1 = SUCC[_0]
  type _2 = SUCC[_1]
  type _3 = SUCC[_2]
  type _4 = SUCC[_3]
  type _5 = SUCC[_4]
  type _6 = SUCC[_5]

  trait ADD[n &lt;: NAT, m &lt;: NAT] extends NAT {
    type a[s[_ &lt;: NAT] &lt;: NAT, z &lt;: NAT] = n#a[s, m#a[s, z]]
  }
  trait MUL[n &lt;: NAT, m &lt;: NAT] extends NAT {
    trait curry[n[_[_], _], s[_]] { type f[z] = n[s, z] }
    type a[s[_ &lt;: NAT] &lt;: NAT, z &lt;: NAT] = n#a[curry[m#a, s]#f, z]
  }

  // aliases for nicer syntax
  type +[n &lt;: NAT, m &lt;: NAT] = ADD[n, m]
  type x[n &lt;: NAT, m &lt;: NAT] = MUL[n, m]
}
</pre>
<p>The pre-processor object defines a trait <em>Loop</em> having an <em>apply</em> method which takes a block of code as argument. Again there are two implicit conversion methods. One which converts the zero type to a <em>Loop</em> with an empty <em>apply</em> function. An another one which convert the type <em>N + 1</em> to a a <em>Loop</em> with an <em>apply</em> function which executes the block once and then applies itself to the type <em>N</em>.</p>
<pre class="brush: java;">
object PreProc {
  def LOOP[N] = null.asInstanceOf[N]

  trait Loop[N] {
    def apply(block: =&gt; Unit)
  }

  implicit def loop0(n: ZERO) = new Loop[ZERO] {
    def apply(block: =&gt; Unit) { }
  }

  implicit def loop[N &lt;: NAT](n: SUCC[N])(implicit f: N =&gt; Loop[N]) = new Loop[SUCC[N]] {
    def apply(block: =&gt; Unit) {
      block
      null.asInstanceOf[N].apply(block)
    }
  }
}
</pre>
<p>Again using this is easy and convenient:</p>
<pre class="brush: java;">
object LoopUnroll {
  import PreProc._

  def unrollTest() {
    // The following line needs the -Yrecursion 1 flag
    // LOOP[(_3 x _2)#v] {
    LOOP[_6] {
      println(&quot;hello world&quot;)
    }
  }

  def main(args: Array[String]) {
    unrollTest()
  }
}
</pre>
<p>The above code prints the string &#8220;hello word&#8221; six times to the console.</p>
<h3>Conclusion</h3>
<p>Scala&#8217;s type system is powerful enough for encoding commonly encountered functions. Together with Scala&#8217;s strong capability for creating internal DSLs, this results in convenient techniques for static meta-programming. Such techniques can be applied to practical problems &#8211; at least in theory. In practice Scala&#8217;s support is not (yet?) there. For one the technique presented here depends on an experimental compiler flag (-Yrecursion). Further the types required for meta-programming might causes an <a href="http://lampsvn.epfl.ch/trac/scala/ticket/1327">exponential growth in compilation time</a> which is not desirable. And finally an analysis with <a href="https://c1visualizer.dev.java.net">c1visualizerwith</a> showed, that the compiler seems not to remove all unnecessary calls. </p>
Posted in Uncategorized Tagged: Meta-Programming, Scala <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/michid.wordpress.com/89/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/michid.wordpress.com/89/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/michid.wordpress.com/89/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/michid.wordpress.com/89/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/michid.wordpress.com/89/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/michid.wordpress.com/89/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/michid.wordpress.com/89/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/michid.wordpress.com/89/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/michid.wordpress.com/89/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/michid.wordpress.com/89/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=michid.wordpress.com&blog=2538862&post=89&subd=michid&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://michid.wordpress.com/2008/10/29/meta-programming-with-scala-conditional-compilation-and-loop-unrolling/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
	
		<media:content url="" medium="image">
			<media:title type="html">michid</media:title>
		</media:content>
	</item>
		<item>
		<title>Meta-Programming with Scala Part III: Partial function application</title>
		<link>http://michid.wordpress.com/2008/08/27/meta-programming-with-scala-part-iii-partial-function-application/</link>
		<comments>http://michid.wordpress.com/2008/08/27/meta-programming-with-scala-part-iii-partial-function-application/#comments</comments>
		<pubDate>Wed, 27 Aug 2008 22:35:06 +0000</pubDate>
		<dc:creator>michid</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Generics]]></category>
		<category><![CDATA[Meta-Programming]]></category>
		<category><![CDATA[Scala]]></category>

		<guid isPermaLink="false">http://michid.wordpress.com/?p=71</guid>
		<description><![CDATA[
In my previous post about Meta-Programming with Scala I suspected that there was no way to express partial function application in Scala&#8217;s type system. However Matt Hellige proofed me wrong in his comment.


His solution uses a trait for partially applying a function to some of its arguments. An abstract type exposed by the trait represents [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=michid.wordpress.com&blog=2538862&post=71&subd=michid&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>
In my <a href="http://michid.wordpress.com/2008/07/30/meta-programming-with-scala-part-ii-multiplication/">previous post</a> about <a href="http://en.wikipedia.org/wiki/Metaprogramming">Meta-Programming</a> with <a href="http://www.scala-lang.org/">Scala</a> I suspected that there was no way to express partial function application in Scala&#8217;s type system. However <a href="http://matt.immute.net/">Matt Hellige</a> proofed me wrong in his <a href="http://michid.wordpress.com/2008/07/30/meta-programming-with-scala-part-ii-multiplication/#comment-69">comment</a>.
</p>
<p>
His solution uses a <a href="http://www.scala-lang.org/node/126">trait</a> for partially applying a function to some of its arguments. An <a href="http://www.scala-lang.org/node/105">abstract type</a> exposed by the trait represents the resulting function which takes the remaining arguments.
</p>
<pre class="brush: java;">
object Partial {
  // Partial application of f2 to x
  trait papply[f2[_, _], x] {
    type f1[y] = f2[x, y]
  }

  // apply f to x
  type apply[f[_], x] = f[x]

  trait X
  trait Y
  trait F[A1, A2]

  // Test whether applying the partial application of
  // F to X to Y equals in the type F[X, Y]
  case class Equals[A &gt;: B &lt;: B, B]
  Equals[apply[papply[F, X]#f1, Y], F[X, Y]]
}
</pre>
<p>
Having this solved we can define a type which encodes <a href="http://michid.wordpress.com/2008/07/30/meta-programming-with-scala-part-ii-multiplication/">multiplication on the Church Numerals</a>.
</p>
<pre class="brush: java;">
    trait curry[n[_[_], _], s[_]] {
      type f[z] = n[s, z]
    }

    // Multiplication for this encoding
    type mult[m[_[_], _], n[_[_], _], s[_], z] = m[curry[n, s]#f, z]
</pre>
<p>
A full working example is available from my <a href="http://michid.wordpress.com/code/meta-programming-with-scala-multiplication/">code page</a>. Note, the code takes forever (i.e. some minutes) to compile. Matt also noted an <a href="http://www.nabble.com/compiler-weirdness-with-crazy-types-td18781474.html">issue with squares</a>. With my version of the compiler (Ecipse plugin 2.7.2.r15874-b20080821120313) the issue does not show up however.</p>
<img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/michid.wordpress.com/71/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/michid.wordpress.com/71/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/michid.wordpress.com/71/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/michid.wordpress.com/71/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/michid.wordpress.com/71/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/michid.wordpress.com/71/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/michid.wordpress.com/71/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/michid.wordpress.com/71/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/michid.wordpress.com/71/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/michid.wordpress.com/71/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/michid.wordpress.com/71/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/michid.wordpress.com/71/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=michid.wordpress.com&blog=2538862&post=71&subd=michid&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://michid.wordpress.com/2008/08/27/meta-programming-with-scala-part-iii-partial-function-application/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="" medium="image">
			<media:title type="html">michid</media:title>
		</media:content>
	</item>
		<item>
		<title>Type-safe Builder Pattern in Java</title>
		<link>http://michid.wordpress.com/2008/08/13/type-safe-builder-pattern-in-java/</link>
		<comments>http://michid.wordpress.com/2008/08/13/type-safe-builder-pattern-in-java/#comments</comments>
		<pubDate>Wed, 13 Aug 2008 21:00:26 +0000</pubDate>
		<dc:creator>michid</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Generics]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Pattern]]></category>

		<guid isPermaLink="false">http://michid.wordpress.com/?p=64</guid>
		<description><![CDATA[In this post I deviate a bit from the topic of my recent posts about Meta-Programming with Scala. I will have more to say about the latter topic in upcoming posts however. 
Recently I read this rather fascinating post about a Type-safe Builder Pattern in Scala. When Heinz Kabutz mentioned the builder pattern in his [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=michid.wordpress.com&blog=2538862&post=64&subd=michid&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>In this post I deviate a bit from the topic of my <a href="http://michid.wordpress.com/2008/04/18/meta-programming-with-scala-part-i-addition/">recent</a> <a href="http://michid.wordpress.com/2008/07/30/meta-programming-with-scala-part-ii-multiplication/">posts</a> about Meta-Programming with <a href="http://www.scala-lang.org/">Scala</a>. I will have more to say about the latter topic in upcoming posts however. </p>
<p>Recently I read this rather fascinating post about a <a href="http://blog.rafaelferreira.net/2008/07/type-safe-builder-pattern-in-scala.html">Type-safe Builder Pattern in Scala</a>. When <a href="http://www.javaspecialists.eu/index.jsp">Heinz Kabutz</a> mentioned the <a href="http://en.wikipedia.org/wiki/Builder_pattern">builder pattern</a> in his <a href="http://www.javaspecialists.eu/archive/Issue163.html">latest issues</a> of the <a href="http://www.javaspecialists.eu/archive/archive.jsp">The Java Specialists’ Newsletter</a> I decided to try to come up with a type safe version for Java. </p>
<p>What I finally came up with is not strictly a builder but something I rather call an initializer. The initializer contains the initial state required by the target object. The state is accumulated within the initializer. Only when the state is complete can it be passed to the targets object&#8217;s constructor. Java&#8217;s type system prevents passing a initializer with an incomplete state to the target class&#8217;s constructor.</p>
<pre class="brush: java;">
public class Foo {
  private final int a;
  private final int b;

  public Foo(Initializer&lt;TRUE, TRUE&gt; initializer) {
    this(initializer.a, initializer.b);
  }

  private Foo(int a, int b) {
    super();
    this.a = a;
    this.b = b;
  }

  public String toString() {
    return &quot;a = &quot; + a + &quot;, b = &quot; + b;
  }

  public static class Initializer&lt;HA, HB&gt; {
    private int a;
    private int b;

    private Initializer() {
      super();
    }

    private Initializer(int a, int b) {
      super();
      this.a = a;
      this.b = b;
    }

    public static Initializer&lt;FALSE, FALSE&gt;create() {
      return new Initializer&lt;FALSE, FALSE&gt;();
    }

    public Initializer&lt;TRUE, HB&gt; setA(int a) {
      this.a = a;
      return new Initializer&lt;TRUE, HB&gt;(a, this.b);
    }

    public Initializer&lt;HA, TRUE&gt; setB(int b) {
      this.b = b;
      return new Initializer&lt;HA, TRUE&gt;(this.a, b);
    }

    static abstract class TRUE {}
    static abstract class FALSE {}
  }

}
</pre>
<p>The basic technique is the same as for the <a href="http://blog.rafaelferreira.net/2008/07/type-safe-builder-pattern-in-scala.html">Type-safe Builder Pattern in Scala</a>: the phantom types <em>TRUE</em> and <em>FALSE</em> are used to keep track of the state. Only a complete state will result in a <em>Initialiter</em> instance which subsequently can be passed to <em>Foo</em>&#8217;s constructor.</p>
<p>Here is how this is used:</p>
<pre class="brush: java;">
public class Main {
  public static void main(String[] args) {
    Initializer&lt;?, ?&gt; initializer = Initializer.create();

    // Foo.create(initializer);           // won't compile
    // Foo.create(initializer.setB(1));   // won't compile
    // Foo.create(initializer.setA(1));   // won't compile

    Foo foo = new Foo(initializer.setA(1).setB(2));
    System.out.println(foo);
  }
}
</pre>
<img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/michid.wordpress.com/64/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/michid.wordpress.com/64/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/michid.wordpress.com/64/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/michid.wordpress.com/64/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/michid.wordpress.com/64/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/michid.wordpress.com/64/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/michid.wordpress.com/64/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/michid.wordpress.com/64/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/michid.wordpress.com/64/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/michid.wordpress.com/64/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/michid.wordpress.com/64/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/michid.wordpress.com/64/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=michid.wordpress.com&blog=2538862&post=64&subd=michid&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://michid.wordpress.com/2008/08/13/type-safe-builder-pattern-in-java/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
	
		<media:content url="" medium="image">
			<media:title type="html">michid</media:title>
		</media:content>
	</item>
		<item>
		<title>Meta-Programming with Scala Part II: Multiplication</title>
		<link>http://michid.wordpress.com/2008/07/30/meta-programming-with-scala-part-ii-multiplication/</link>
		<comments>http://michid.wordpress.com/2008/07/30/meta-programming-with-scala-part-ii-multiplication/#comments</comments>
		<pubDate>Wed, 30 Jul 2008 21:07:57 +0000</pubDate>
		<dc:creator>michid</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Meta-Programming]]></category>
		<category><![CDATA[Scala]]></category>

		<guid isPermaLink="false">http://michid.wordpress.com/?p=41</guid>
		<description><![CDATA[This was sitting on my desk for quite a while now while I was busy with other things. Finally I came around to write things up.
In my last post I showed how to encode the Church numerals and addition on them with Scala&#8217;s type system. I mentioned that this approach does not seem to scale. [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=michid.wordpress.com&blog=2538862&post=41&subd=michid&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>This was sitting on my desk for quite a while now while I was busy with other things. Finally I came around to write things up.</p>
<p>In my <a href="http://michid.wordpress.com/2008/04/18/meta-programming-with-scala-part-i-addition/">last post</a> I showed how to encode the <a href="http://en.wikipedia.org/wiki/Church_encoding">Church numerals</a> and addition on them with <a href="http://www.scala-lang.org/">Scala&#8217;s</a> type system. I mentioned that this approach does not seem to scale. In this post I show the problems I faced while I tried to extend the approach to multiplication. This particular example shows that Scala&#8217;s type system does not seem to support partial function application which in general is crucial for defining more complex functions base on simpler ones. But before delving into Scala, let&#8217;s review the church numerals in <a href="http://en.wikipedia.org/wiki/Lambda_calculus">lambda calculus</a>. </p>
<p>Define a lambda term for each natural number <i>n</i></p>
<p><img src='http://l.wordpress.com/latex.php?latex=0%5Cequiv%5Clambda+sz.z&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='0\equiv\lambda sz.z' title='0\equiv\lambda sz.z' class='latex' /><br />
<img src='http://l.wordpress.com/latex.php?latex=1%5Cequiv%5Clambda+sz.sz&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='1\equiv\lambda sz.sz' title='1\equiv\lambda sz.sz' class='latex' /><br />
<img src='http://l.wordpress.com/latex.php?latex=2%5Cequiv%5Clambda+sz.ssz&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='2\equiv\lambda sz.ssz' title='2\equiv\lambda sz.ssz' class='latex' /><br />
<img src='http://l.wordpress.com/latex.php?latex=%5Ccdots+&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\cdots ' title='\cdots ' class='latex' />  &nbsp;<br />
<img src='http://l.wordpress.com/latex.php?latex=n%5Cequiv%5Clambda+sz.s%5Enz&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='n\equiv\lambda sz.s^nz' title='n\equiv\lambda sz.s^nz' class='latex' /></p>
<p>where <img src='http://l.wordpress.com/latex.php?latex=s%5En+&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='s^n ' title='s^n ' class='latex' /> stands for the <i>n</i>-fold application of <i>s</i>. Think of <i>s</i> standing for successor and <i>z</i> for zero. Then the number <i>n</i> is simply the <i>n</i>-fold successor of zero.</p>
<p>Addition can now be define as </p>
<p><img src='http://l.wordpress.com/latex.php?latex=add+%5Cequiv+%5Clambda+mnsz.ms%28nsz%29+&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='add \equiv \lambda mnsz.ms(nsz) ' title='add \equiv \lambda mnsz.ms(nsz) ' class='latex' />.</p>
<p>Here the <i>n</i>-fold successor of zero is used as zero element for <i>m</i>. Again this can be thought of as the <i>m</i>-fold successor of the <i>n</i>-fold successor of zero.</p>
<p>Multiplications is similar but instead of using <em>a different value for zero</em>, a <em>different successor function</em> is used:</p>
<p><img src='http://l.wordpress.com/latex.php?latex=mul+%5Cequiv+%5Clambda+mnsz.m%28ns%29+&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='mul \equiv \lambda mnsz.m(ns) ' title='mul \equiv \lambda mnsz.m(ns) ' class='latex' /></p>
<p>This boils down to the <i>m</i>-fold application of the <i>n</i>-fold successor function.</p>
<p>As in my <a href="http://michid.wordpress.com/2008/04/18/meta-programming-with-scala-part-i-addition/">previous post</a> the Church numerals are encoded in Scala&#8217;s type system as follows</p>
<pre class="brush: java;">
type _0[s[_], z] = z
type _1[s[_], z] = s[z]
type _2[s[_], z] = s[s[z]]
type _3[s[_], z] = s[s[s[z]]]
type _4[s[_], z] = s[s[s[s[z]]]]
</pre>
<p>I did not succeed encoding multiplication however. The most straight forward encoding &#8211; which closely follows the one for addition &#8211; looks like this</p>
<pre class="brush: java;">
type mul[m[s[_], z], n[s[_], z], s[_], z] = m[n[s[_], z], z]
</pre>
<p>However the Scala compiler complains:</p>
<pre>
  s[_$1] forSome { type _$1 } takes no type parameters,
  expected: one
</pre>
<p>Unlike addition, we need to pass a partially applied function here &#8211; namely the <i>n</i>-fold successor function. Since the above does not work, I&#8217;m not sure if there even is a syntax for expressing partial function application in Scala&#8217;s type system.</p>
<p>In another approach I tried to introducing a formal parameter for the <i>n</i>-fold successor function:</p>
<pre class="brush: java;">
type mul[m[n[s[_], z], z], n[s[_], z], s[_], z] = m[n, z]
</pre>
<p>The compiler does not complain here which is encouraging. However this breaks on application</p>
<pre class="brush: java;">
abstract class Zero
abstract class Succ[T]

type zero = mul[_0, _0, Succ, Zero]
type one = mul[_1, _3, Succ, Zero]
</pre>
<p>The first application results in a kind error</p>
<pre>
the kinds of the type arguments (Meta._0,Meta._0,Meta.Succ,Meta.Zero) do not conform to
the expected kinds of the type parameters (type m,type n,type s,type z).
Meta._0's type parameters do not match type m's expected parameters:
type s has one type parameter, but type n has two
</pre>
<p>The second application causes an assertion failure of the Scala compiler (see <a href="http://lampsvn.epfl.ch/trac/scala/ticket/742">Ticket #742</a>). </p>
<p>For a better understanding let&#8217;s analyze what <i>mul[_1, _3, Succ, Zero]</i> expands to:</p>
<pre class="brush: java;">
mul[_1, _3, Succ, Zero] =
_1[_3, Zero] =
_3[Zero]
</pre>
<p>While this looks somewhat correct, it is certainly not. <i>_3</i> takes two arguments but gets one. This is exactly what the Scala compiler was complaining about. </p>
<img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/michid.wordpress.com/41/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/michid.wordpress.com/41/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/michid.wordpress.com/41/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/michid.wordpress.com/41/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/michid.wordpress.com/41/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/michid.wordpress.com/41/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/michid.wordpress.com/41/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/michid.wordpress.com/41/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/michid.wordpress.com/41/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/michid.wordpress.com/41/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/michid.wordpress.com/41/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/michid.wordpress.com/41/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=michid.wordpress.com&blog=2538862&post=41&subd=michid&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://michid.wordpress.com/2008/07/30/meta-programming-with-scala-part-ii-multiplication/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
	
		<media:content url="" medium="image">
			<media:title type="html">michid</media:title>
		</media:content>
	</item>
		<item>
		<title>Meta-Programming with Scala Part I: Addition</title>
		<link>http://michid.wordpress.com/2008/04/18/meta-programming-with-scala-part-i-addition/</link>
		<comments>http://michid.wordpress.com/2008/04/18/meta-programming-with-scala-part-i-addition/#comments</comments>
		<pubDate>Fri, 18 Apr 2008 15:15:57 +0000</pubDate>
		<dc:creator>michid</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Meta-Programming]]></category>
		<category><![CDATA[Scala]]></category>

		<guid isPermaLink="false">http://michid.wordpress.com/?p=22</guid>
		<description><![CDATA[In the solution to a puzzle I posted earlier, I mentioned that the taken approach might be a first step towards meta-programming in Scala. 
While the approach to determine the depth of a type plays nicely with the Church encodings of natural numbers proposed in the paper Towards Equal Rights for Higher-kinded Types, defining arbitrary [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=michid.wordpress.com&blog=2538862&post=22&subd=michid&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>In the <a href="http://michid.wordpress.com/2008/03/12/puzzle-the-depth-of-a-type-solution/">solution</a> to a <a href="http://michid.wordpress.com/2008/03/04/puzzle-the-depth-of-a-type/">puzzle</a> I posted earlier, I mentioned that the taken approach might be a first step towards <a href="http://en.wikipedia.org/wiki/Metaprogramming">meta-programming</a> in Scala. </p>
<p>While the approach to <a href="http://michid.wordpress.com/2008/03/12/puzzle-the-depth-of-a-type-solution/">determine the depth of a type</a> plays nicely with the <a href="http://en.wikipedia.org/wiki/Church_encoding">Church encodings</a> of natural numbers proposed in the paper <a href="http://www.cs.kuleuven.be/~adriaan/files/higher.pdf">Towards Equal Rights for Higher-kinded Types</a>, defining arbitrary arithmetic operators seems problematic. Addition does not pose a problem. But there seems to be no easy generalization to other arithmetic operators. This is despite the fact that the authors of the above paper mention that Scala&#8217;s kinds correspond to the types of the simply typed lambda calculus. </p>
<p>In this post I will explain how to represent the natural numbers and an addition operator using Scala&#8217;s type system. In a later post I will show why this approach does not easily scale to the other arithmetic operators like multiplication and why I think that this might not be a problem of Scala&#8217;s type system in general but rather a shortcoming of its syntax. Finally I noted that <a href="http://www.scala-lang.org/downloads/changes.html#v2.7.1.RC1">Scala 2.7.1.RC1</a> dropped the contractiveness requirement for <a href="http://www.scala-lang.org/intro/implicit.html">implicits</a>. This might open up another way for meta-programming. I probably write more on this in yet another post.</p>
<p>The following code shows a <a href="http://en.wikipedia.org/wiki/Church_encoding">Church encoding</a> of the natural numbers in Scala&#8217;s type system. (The <a href="http://michid.wordpress.com/code/meta-programming-with-scala-part-i-addition/">full source</a> is available from my <a href="http://michid.wordpress.com/code/">code page</a>).</p>
<pre class="brush: java;">
  type _0[s[_], z] = z
  type _1[s[_], z] = s[z]
  type _2[s[_], z] = s[s[z]]
  type _3[s[_], z] = s[s[s[z]]]
	// ...
</pre>
<p>A natural numbers is encoded as a type function which takes two arguments: a successor function and a zero element. The <i>n</i>-th natural number is then the <i>n</i>-fold application of the successor function to the zero element. Such natural numbers can be instantiated by passing them an actual type for its successor function and its zero element. The <i>depth</i> function form <a href="http://michid.wordpress.com/2008/03/12/puzzle-the-depth-of-a-type-solution/">my last post</a> can then be used to evaluate such a number; </p>
<pre class="brush: java;">
  abstract class Zero
  abstract class Succ[T]
  type two = _2[Succ, Zero]
  println(depth(nullval[two]))  // prints 2
</pre>
<p>We can now define an addition operator like this:</p>
<pre class="brush: java;">
  type plus[m[s[_], z], n[s[_], z], s[_], z] = n[s, m[s, z]]
  type +[m[s[_], z], n[s[_], z]] = plus[m, n, Succ, Zero]
</pre>
<p>Basically <i>plus</i> takes two Church numerals <i>n</i> and <i>m</i> and composes them such that <i>m</i> becomes the zero element of <i>n</i>. The second line defines an infix <i>+</i> operator:</p>
<pre class="brush: java;">
  println(depth(nullval[_2 + _2])) // prints 4
  println(depth(nullval[_2 + _3])) // prints 5
</pre>
<p>Let&#8217;s analyze in detail what <i>_2 + _3</i> expands to in order to better understand above code:</p>
<pre class="brush: java;">
  _2 + _3 =
	plus[_2, _3, Succ, Zero] =
	_3[Succ, _2[Succ, Zero]] =
	_3[Succ, Succ[Succ[Zero]]] =
	Succ[Succ[Succ[Succ[Succ[Zero]]]]]
</pre>
<p>So passing <i>_2 + _3</i> to the <i>depth</i> function will indeed print <i>5</i> since this its structural depth.</p>
<p>From here one might want to generalize this to other arithmetic operations. I tried multiplication but failed so far. In a next post I will explain my closest shot(s) at multiplication and I will explain what I think are the difficulties with this approach.</p>
<img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/michid.wordpress.com/22/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/michid.wordpress.com/22/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/michid.wordpress.com/22/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/michid.wordpress.com/22/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/michid.wordpress.com/22/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/michid.wordpress.com/22/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/michid.wordpress.com/22/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/michid.wordpress.com/22/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/michid.wordpress.com/22/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/michid.wordpress.com/22/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/michid.wordpress.com/22/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/michid.wordpress.com/22/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=michid.wordpress.com&blog=2538862&post=22&subd=michid&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://michid.wordpress.com/2008/04/18/meta-programming-with-scala-part-i-addition/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
	
		<media:content url="" medium="image">
			<media:title type="html">michid</media:title>
		</media:content>
	</item>
	</channel>
</rss>