Scala Beauty – Arabic DSL

Recently I gave a Scala talk at the Egyptian Java Developer Conference, one of the demos that raised most comments was a Lisp like internal Arabic DSL in Scala. I only knew about a few papers that studied the subject and I am no expert in this area, but it turned out that it was pretty interesting for audience to see how simple this can be achieved in Scala, specially that the DSL is internal, so you have the full power of the Scala language with its libraries and all the familiar Java libraries.

There are lots of problems when dealing with Arabic as a programming language, the most challenging one is that Arabic is written from right to left. For Scala, the solution is surprisingly simple, the whole idea was to:

  • Use non-ASCII characters to represent Arabic
  • End method names with a ‘:’ to swap the call and the receiver  positions

The DSL model is basically a recursive Operator/Operand hierarchy, so you can inject operators as needed to be used as operations, with the simple trick: An Operator is an Operand.

trait Opn
trait Opt extends Opn {
  def -:(opn: Opn): Opn
}

The method ‘-:’ is simply our version of ‘apply’, but it looks natural if read from right to left.

Operators are simple Scala case objects that are given Arabic aliases:

object Print extends Opt {
  def -:(opn: Opn) = {
    println(opn)
    this
  }
}

With such model you can also get the sense of dynamic typing, for example:

object Undefined extends Opn

object Reverse extends Opt {
  def -:(opn: Opn) = opn match {
    case Value(l: List[_]) => Value(l.reverse)
    case _ => Undefined
  }
}

Here is a use case of this model:
Scala Arabic DSL

Folks who understand Arabic will appreciate the fluency of the DSL, that executes exactly as it reads.

Advertisements

3 thoughts on “Scala Beauty – Arabic DSL

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s