Puzzle: implement this (solution)

24 06 2009

Well, I wasn’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’t find sever limitations. Maybe someone else does…

When I initially stumbled on this, I remembered that existential types where introduced into Scala for coping with Java’s raw types. But there is an additional twist here, we need to tell the compiler that our MyIterator implementation actually ‘is an instance of a raw type’. So combining existential types with self types led me to the following solution:

class MyIterator extends Iterator2 {
  this: java.util.Iterator[_] =>
  def hasNext = true
  def remove = throw new Error  
  def next = "infinity"   

We can now safely use instances of MyIterator.

  def test1(it: MyIterator) = {
  def test2(it: java.util.Iterator[_]) = {
  val it = new MyIterator
  val v: String = it.next

The approach using existential types in combination with self types makes sure that values returned from the next method always are typed correctly.

Puzzle: implement this

19 06 2009

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 MyIterator extends Iterator2 {
  def hasNext = false
  def remove = throw new Error
  def next: Nothing = throw new Error

But if the next method should return an actual value, what would be it’s return type? It turn’s out that any other type than Nothing results in a compiler error:

error overriding method next in trait Iterator of type ()E;
method next has incompatible type ()Any

So how would you implement Iterator2?

Meta-Programming with Scala: Conditional Compilation and Loop Unrolling

29 10 2008

The kind of comments I keep getting on my static meta-programming with Scala blogs are often along the lines of: “The ability to encode Church Numerals in Scala still seems uselessly academic to me, but cool none-the-less”. In this blog I will show how meta-programming can be applied in practice – at least theoretically.

In my previous blogs I introduced a technique for static meta-programing with Scala. This technique uses Scala’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 addition and multiplication.

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 -Yrecursion 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.

Conditional Compilation

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.

Lets first define meta-booleans and some operations on them (full code here):

object Booleans {
  trait BOOL {
    type a[t <: BOOL, f <: BOOL] <: BOOL
    type v = a[TRUE, FALSE]
  final class TRUE extends BOOL {
    type a[t <: BOOL, f <: BOOL] = t
  final class FALSE extends BOOL{
    type a[t <: BOOL, f <: BOOL] = f
  trait IF[x <: BOOL, y <: BOOL, z <: BOOL] extends BOOL {
    type a[t <: BOOL, f <: BOOL] = x#a[y, z]#a[t, f]
  trait NOT[x <: BOOL] extends BOOL {
    type a[t <: BOOL, f <: BOOL] = IF[x, FALSE, TRUE]#a[t, f]
  trait AND[x <: BOOL, y <: BOOL] extends BOOL {
    type a[t <: BOOL, f <: BOOL] = IF[x, y, FALSE]#a[t, f]
  trait OR[x <: BOOL, y <: BOOL] extends BOOL {
    type a[t <: BOOL, f <: BOOL] = IF[x, TRUE, y]#a[t, f]

  // aliases for nicer syntax
  type ![x <: BOOL] = NOT[x]
  type ||[x <: BOOL, y <: BOOL] = OR[x, y]
  type &&[x <: BOOL, y <: BOOL] = AND[x, y]

The following pre-processor object contains an implicit method for converting a value of type TRUE to an Include object whose apply method executes a block of code. Similarly it contains an implicit method for converting a value of type FALSE to an Exclude object whose apply method simply does nothing. The strange line where null is being cast to B is a trick for getting a witnesses of a value of type B.

object PreProc {
  def IF[B] = null.asInstanceOf[B]

  object Include {
    def apply(block: => Unit) {

  object Exclude {
    def apply(block: => Unit) { }

  implicit def include(t: TRUE) = Include
  implicit def exclude(f: FALSE) = Exclude

Using these definitions is quite convenient now:

object IfDefTest {
  import PreProc._

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

  def errTest() {
    IF[(LOG && ERR)#v] {

  def warnTest() {
    IF[(LOG && WARN)#v] {

  def main(args: Array[String]) {

Running the above code will print err but wont print warn to the console.

Loop Unrolling

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.

Again let’s first define meta-naturals and their operations (full code here):

object Naturals {
  trait NAT {
    type a[s[_ <: NAT] <: NAT, z <: NAT] <: NAT
    type v = a[SUCC, ZERO]
  final class ZERO extends NAT {
    type a[s[_ <: NAT] <: NAT, z <: NAT] = z
  final class SUCC[n <: NAT] extends NAT {
    type a[s[_ <: NAT] <: NAT, z <: 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 <: NAT, m <: NAT] extends NAT {
    type a[s[_ <: NAT] <: NAT, z <: NAT] = n#a[s, m#a[s, z]]
  trait MUL[n <: NAT, m <: NAT] extends NAT {
    trait curry[n[_[_], _], s[_]] { type f[z] = n[s, z] }
    type a[s[_ <: NAT] <: NAT, z <: NAT] = n#a[curry[m#a, s]#f, z]

  // aliases for nicer syntax
  type +[n <: NAT, m <: NAT] = ADD[n, m]
  type x[n <: NAT, m <: NAT] = MUL[n, m]

The pre-processor object defines a trait Loop having an apply method which takes a block of code as argument. Again there are two implicit conversion methods. One which converts the zero type to a Loop with an empty apply function. An another one which convert the type N + 1 to a a Loop with an apply function which executes the block once and then applies itself to the type N.

object PreProc {
  def LOOP[N] = null.asInstanceOf[N]

  trait Loop[N] {
    def apply(block: => Unit)

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

  implicit def loop[N <: NAT](n: SUCC[N])(implicit f: N => Loop[N]) = new Loop[SUCC[N]] {
    def apply(block: => Unit) {

Again using this is easy and convenient:

object LoopUnroll {
  import PreProc._

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

  def main(args: Array[String]) {

The above code prints the string “hello word” six times to the console.


Scala’s type system is powerful enough for encoding commonly encountered functions. Together with Scala’s strong capability for creating internal DSLs, this results in convenient techniques for static meta-programming. Such techniques can be applied to practical problems – at least in theory. In practice Scala’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 exponential growth in compilation time which is not desirable. And finally an analysis with c1visualizerwith showed, that the compiler seems not to remove all unnecessary calls.

Meta-Programming with Scala Part III: Partial function application

27 08 2008

In my previous post about Meta-Programming with Scala I suspected that there was no way to express partial function application in Scala’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 the resulting function which takes the remaining arguments.

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 >: B <: B, B]
  Equals[apply[papply[F, X]#f1, Y], F[X, Y]]

Having this solved we can define a type which encodes multiplication on the Church Numerals.

    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]

A full working example is available from my code page. Note, the code takes forever (i.e. some minutes) to compile. Matt also noted an issue with squares. With my version of the compiler (Ecipse plugin 2.7.2.r15874-b20080821120313) the issue does not show up however.

Meta-Programming with Scala Part II: Multiplication

30 07 2008

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’s 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’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’s review the church numerals in lambda calculus.

Define a lambda term for each natural number n

0\equiv\lambda sz.z
1\equiv\lambda sz.sz
2\equiv\lambda sz.ssz
n\equiv\lambda sz.s^nz

where s^n stands for the n-fold application of s. Think of s standing for successor and z for zero. Then the number n is simply the n-fold successor of zero.

Addition can now be define as

add \equiv \lambda mnsz.ms(nsz) .

Here the n-fold successor of zero is used as zero element for m. Again this can be thought of as the m-fold successor of the n-fold successor of zero.

Multiplications is similar but instead of using a different value for zero, a different successor function is used:

mul \equiv \lambda mnsz.m(ns)

This boils down to the m-fold application of the n-fold successor function.

As in my previous post the Church numerals are encoded in Scala’s type system as follows

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]]]]

I did not succeed encoding multiplication however. The most straight forward encoding – which closely follows the one for addition – looks like this

type mul[m[s[_], z], n[s[_], z], s[_], z] = m[n[s[_], z], z]

However the Scala compiler complains:

  s[_$1] forSome { type _$1 } takes no type parameters, 
  expected: one

Unlike addition, we need to pass a partially applied function here – namely the n-fold successor function. Since the above does not work, I’m not sure if there even is a syntax for expressing partial function application in Scala’s type system.

In another approach I tried to introducing a formal parameter for the n-fold successor function:

type mul[m[n[s[_], z], z], n[s[_], z], s[_], z] = m[n, z]

The compiler does not complain here which is encouraging. However this breaks on application

abstract class Zero
abstract class Succ[T]

type zero = mul[_0, _0, Succ, Zero] 
type one = mul[_1, _3, Succ, Zero] 

The first application results in a kind error

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	

The second application causes an assertion failure of the Scala compiler (see Ticket #742).

For a better understanding let’s analyze what mul[_1, _3, Succ, Zero] expands to:

mul[_1, _3, Succ, Zero] =
_1[_3, Zero] =

While this looks somewhat correct, it is certainly not. _3 takes two arguments but gets one. This is exactly what the Scala compiler was complaining about.

Meta-Programming with Scala Part I: Addition

18 04 2008

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 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’s kinds correspond to the types of the simply typed lambda calculus.

In this post I will explain how to represent the natural numbers and an addition operator using Scala’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’s type system in general but rather a shortcoming of its syntax. Finally I noted that Scala 2.7.1.RC1 dropped the contractiveness requirement for implicits. This might open up another way for meta-programming. I probably write more on this in yet another post.

The following code shows a Church encoding of the natural numbers in Scala’s type system. (The full source is available from my code page).

  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]]]
	// ...

A natural numbers is encoded as a type function which takes two arguments: a successor function and a zero element. The n-th natural number is then the n-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 depth function form my last post can then be used to evaluate such a number;

  abstract class Zero
  abstract class Succ[T]
  type two = _2[Succ, Zero] 
  println(depth(nullval[two]))  // prints 2

We can now define an addition operator like this:

  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]

Basically plus takes two Church numerals n and m and composes them such that m becomes the zero element of n. The second line defines an infix + operator:

  println(depth(nullval[_2 + _2])) // prints 4
  println(depth(nullval[_2 + _3])) // prints 5

Let’s analyze in detail what _2 + _3 expands to in order to better understand above code:

  _2 + _3 =
	plus[_2, _3, Succ, Zero] =
	_3[Succ, _2[Succ, Zero]] =
	_3[Succ, Succ[Succ[Zero]]] =

So passing _2 + _3 to the depth function will indeed print 5 since this its structural depth.

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.

Puzzle: the depth of a type (solution)

12 03 2008

In my previous post I asked for a function depth, which takes an argument of type M and returns its structural depth.

Here is my solution:

object Puzzle {
  class M[T]
  abstract class Rep[T] {
    def eval: int
  implicit def toRep0[T](k: T) = new Rep[T] {
    def eval = 0
  implicit def toRepN[T](k: M[T])(implicit f: T => Rep[T]) = new Rep[M[T]] {
    def eval = f(null.asInstanceOf[T]).eval + 1

  def depth[T <% Rep[T]](m: T) = m.eval
  def main(args: Array[String]) {
    println(depth(new M[int]))
    println(depth(new M[M[int]]))
    println(depth(new M[M[M[int]]]))

This is the same technique as discussed in my articles on implicit double dispatch. The function depth is applicable to any argument of type T which is implicitly convertible to type Rep[T]. Rep[T] instances implement a function eval, which returns the depth of the type this instance is representing. There are two function for implicit conversions: toRep0 and toRepN. The toRep0 function is responsible for the base case where the structural depth of the type of its argument is 0. The eval function thus returns 0 in this case. The toRepN function is responsible for the other cases where a Mn + 1[T] has to be converted into a Rep[Mn + 1[T]] (Mk[T] stands for M[M[…[T]]] having structural depth k). toRepN takes an implicit parameter f itself. This parameter is a conversion function for converting a Mn[T] into a Rep[Mn[T]] which is used for constructing Rep[Mn + 1[T]]. Since we can convert types of structural depths 0 and types of structural depth n + 1 when given a Rep[T] for T having structural depths n, we can – by induction – convert types of any structural depth.

The implementation of eval in toRepN is implemented in terms of the eval method of Rep[T]. However to access Rep[T] we need to apply f to a T. Since we don’t have an instance of T and since the actual instance does not matter, we simply pass null casted to T.

The technique employed here is a special case of the Code Follows Type pattern. The general idea is not to re-implement the structure of types in code, but to re-use the inherent information carried by types. While in Java this is only possible to a limited degree, Scala’s implicit conversions enable this technique even for recursive structures.

Credits are due to Henry Ware for pointing me to this paper about Scala’s higher kinds. Towards the end of the paper the authors show how to encode the church numerals as Scala types. The encoding plays nicely with the depth function. So – as I mentioned before in a comment – this might be a first, gentle step towards meta-programming with Scala. However, there are certain limitations I guess. I will write more about this later.

Puzzle: the depth of a type

4 03 2008

Here is a little Scala quiz I made up: say we have a type M[T]. Design a function depth which takes an argument of type M and returns its structural depth.

class M[T]

def depth ...

def main(args: Array[String]) {
  println(depth(new M[int]))
  println(depth(new M[M[int]]))
  println(depth(new M[M[M[int]]]))

So with the right definition of depth in place the above code should print


I’m not sure if this can be done through pattern matching or using instanceOf. My solution does not rely on either of these.

Implicit double dispatch revisited

8 02 2008

In my first post on this topic I showed how generic types can be treated polymorphically in Scala. I employed Scala’s implicits and view bounds to emulate overloading of methods with arguments having the same type erasure.

def foo[T <% Dispatcher[T]](x: T) {
  x.dispatch(new Switch {
    def case_(x: String) {
      println("Got a string " + x)                
    def case_(x: int) {
      println("Got a int " + x)

Method foo can be called for any type T for which a conversion to the type Dispatcher[T] is in scope. Dispatcher[T] has a dispatch method for the type T. The method takes a Switch instance and calls its case_ method passing along the dispatched value. See Implicit double dispatch for details.

trait Switch {
  def case_(s: String)
  def case_(n: int)

There are two things I don’t like. First, when calling foo with a list argument the list is not passed on as a whole to the respective case_ method. Rather is the case_ method called once for every element of the list iteratively. Second, the foo method is also callable with arguments of type String and type int, not only for Lists of these types.

I generalized my initial code to address these issues. The revisited code is again available on my code page.

To address the first issue I simplified the implementation of foo to

def foo[T <% Dispatcher[T]](x: T) = x.dispatch()

The signature is as before and allows foo to be called for all types T which are implicitly convertible to Dispatcher[T]. The implementation is much simpler however. It still calls the dispatch method of its Dispatcher[T] argument but this time without an argument.

abstract class Dispatcher[T](value: T) {
  def dispatch()
  def dispatch(l: List[T])

Again Dispatcher[T] is responsible for handling values of type T. But now there is an additional dispatch method for handling lists of values of type T. The implicit conversion methods create specialized Dispatcher[T] instances for concretes types.

implicit def string2Disp(value: String) = new Dispatcher(value){
  def dispatch() = println("String: " + value)
  def dispatch(l: List[String]) =  println("List[String]: " + l)

The above code is for converting a String to a Dispatcher[String]. (Converting an int to a Dispatcher[int] works analogous). The method returns a new instance of type Dispatcher[String] whose dispatch methods outputs the original value. For the first method this is the value originally passed to string2Disp. For the second method the value is a list of strings passed as argument. To see how this second method is called and where that list argument comes from let’s take a look at how lists are converted to their respective Dispatcher objects.

implicit def list2Disp[T](value: List[T])(implicit x2Disp: T => Dispatcher[T]) = new Dispatcher(value) {
  def dispatch() = x2Disp(null.asInstanceOf[T]).dispatch(value)
  def dispatch(l: List[List[T]]) = println("List[List[_]]: " + l)        

Say a List[String] is to be converted to Dispatcher[List[String]]. The Scala compiler looks for an implicit argument to be passed for the x2Disp parameter. It finds the string2Disp method and passes it for the x2Disp parameter. Now there is a trick in the implementation of the first dispatch method: a call to x2Disp returns an instance of Dispatcher[String] which is subsequently used to call dispatch on passing along the original list of strings. The argument passed to x2Disp does not matter since any instance of Dispatcher[String] will do. So we simply pass null casted to the right type T.
The second dispatch method which takes a list of lists is similar to the dispatch method for lists in the case of Dispatcher[String] from above. The dispatch mechanism thus works for arguments of type List[List[List[...]]] up to an arbitrary depth (at least in theory).

To address the second issues, all that has to be done is to further restrict the applicable types for the foo method. Such a restriction should only allow lists to be passed as arguments, not individual values. I did not succeed to express such a constraint as an upper bound along the lines of

def foo[T <% Dispatcher[T] <: List[T]](x: T) = x.dispatch()

or similarly. However using existential types the same effect can be achieved:

def foo[T <% Dispatcher[T] forSome { type T <: List[_] }](x: T) = x.dispatch()

This effectively limits type T further to lists convertible to Dispatcher[T]. With this signature in place the following calls to foo are not legal anymore

foo("A String")

while all of the following still works as expected:

val ints: List[int] = Nil
foo(ints)     // empty list of ints
val strings: List[String] = Nil
foo(strings)  // empty list of strings

// Simple lists

// List of lists

Finally one may ask: where is the double dispatch? Well, it is hidden inside the implicit argument passed to list2Disp. The first dispatch is explicitly done by the foo method. If we deal with a list, the second dispatch is done on the object returned by the call to the x2Disp argument which was implicitly passed on the first dispatch.

adding nodes in ASCII art – part 2

31 01 2008

I wrote a follow up on my article JCR with Scala: adding nodes in ASCII art over at my employers blog.

I discuss the goals I had in mind when designing the ‘ASCII art’ operators. This helps in understanding how these operators actually work and serve as preparation for a later post where I will show how properties fit into the picture.


Get every new post delivered to your Inbox.