Posts Tagged 'metaprogramming'

A Deeper Look at the Scala Syntax

Scala is an object-oriented, statically-typed and functional programming language for the JVM. The strength of Scala lies in it’s powerful syntax which allows to write readable, manageable code which is short and concise – and it comes with great support for common design pattern (i.e. a special keyword for implementing the singleton design pattern).

There are plenty of good tutorials and introductions for learning Scala in the web, but only a few mention the great possibilities programmers have to extend Scala or even build an own domain specific language using Scala without being forced to use macros as seen in LISP-like languages.

One interesting feature of Scala are “blocks” which work quite different then code blocks in Java and C++ although they use the same syntax. A block in Scala is rather a sequence of expressions which is evaluated successively and it returns the value of the last expression. Just think of them as the “do” function in LISP. Blocks are surrounded by curly braces and the expressions they hold are separated by semicolons.

scala> {val x = 2; x + 5}
res0: Int = 7

Thanks to some syntactic sugar the semicolon can be replaced by a line break which becomes handy in larger blocks.

scala> {
  val x = 5
  x + 5
res1: Int = 10

Because blocks are just expressions they can be used, of course, like every other expression. They can be stored in variables, returned by functions and also be used as parameters for functions:

scala> println(2+5)

scala> println {
  val x = 2
  x + 5

The attentive reader might already have a glimpse of the potential power of such a syntax. This tiny, simple feature allows us to define functions which look and feel more like keywords of the language’s syntax. Just think of a function which measures the time a given piece of code needs to be executed. How would you write something like this in Java or even in a dynamic language like Python? In Scala this can easily be done by writing a function which expects a code block and handles it like a function which returns a value of any type to simulate lazy parameter evaluation.

def time(code: => Any):Any = {
  val time = System.currentTimeMillis
  val result = code
  println("time elapsed: " + (System.currentTimeMillis-time))

def fib(n:Int):Int = if (n < 2) 1 else fib(n-1)+fib(n-2)

scala> time {

time elapsed: 1020
res2: Any = 165580141

Create New Classes With Python At Runtime

For a testing framework I want to create new classes in Python at runtime:

def mixIn(classname, parentclasses):
	if len(parentclasses) > 0:
		parents = map(lambda p:p.__name__, parentclasses)
		createclass = "class %s (%s):\n\tpass" % (classname, ",".join(parents))
		createclass = "class %s:\n\tpass" % classname
	exec createclass
	globals()[classname] = eval(classname)

This function creates a new class in the global namespace with the name classname inheriting from all classes in parentclasses, which is a list of strings.

Use the function like this:

class Foobar:
	def __init__(self, a):
		self.a = a
	def foo(self):
		return "foo" + str(self.a)

class Barfoo:
	def __init__(self, b, a):
		self.b = b
		self.a = a
	def bar(self):
		return "bar" + str(self.b) + str(self.a)

mixIn("Test", ["Foobar", "Barfoo"])
t = Test("23")
print # this will print "foo23"
print # this will throw an exception, because self.b is not defined

In most cases it’s not possible to generate a meaningful __init__ function automatically. The Python interpreter just takes the constructor of the first parent, but it’s possible to add another constructor afterwards.

def myinit(self, a, b):
	Foobar.__init__(self, a)
	Barfoo.__init__(self, b, a)
Test.__init__ = myinit
t = Test("23", "42")
print # prints foo23
print # prints bar4223