2

In short: I try to write something like A <N B for a DSL in Scala, for an integer N and A,B of Type T. Is there a nice possibility to do so?

Longer: I try to write a DSL for TGrep2 in Scala. I'm currently interested to write

A <N B          B is the Nth child of A (the rst child is <1).

in a nice way and as close as possible to the original definition in Scala. Is there a way to overload the < Operator that it can take a N and a B as a argument.

What I tried: I tried two different possibilities which did not make me very happy:

scala> val N = 10
N: Int = 10

scala> case class T(n:String) {def <(i:Int,j:T) = println("huray!")}
defined class T

scala> T("foo").<(N,T("bar"))
huray!

and

scala> case class T(n:String) {def <(i:Int) = new {def apply(j:T) = println("huray!")}}
defined class T

scala> (T("foo")<N)(T("bar"))
warning: there were 1 feature warnings; re-run with -feature for details
huray!
2
  • 2
    Id suggest you use something like nth instead of the < symbol which makes the semantics clear. A nth N is B would make a lot of sense to me at least.
    – korefn
    Apr 2, 2013 at 7:56
  • 1
    Scala's "operator" syntax sugar allows foo.bar(baz) to become foo bar baz, but it doesn't apply to functions with multiple arguments. You'll want to re-think your DSL so that your statement is more like foo.bar(baz).bang(biff) (A nth N is B)
    – Dylan
    Apr 2, 2013 at 11:20

2 Answers 2

3

Id suggest you use something like nth instead of the < symbol which makes the semantics clear. A nth N is B would make a lot of sense to me at least. It would translate to something like

case class T (label:String){
  def is(j:T) = {
label equals j.label
  }
}

case class J(i:List[T]){
  def nth(index:Int) :T = {
    i(index)
  }
}

You can easily do:

val t  = T("Mice")
val t1 = T("Rats")
val j  = J(List(t1,t))

j nth 1 is t //res = true
0

The problem is that apply doesn't work as a postfix operator, so you can't write it without the parantheses, you could write this:

  case class T(n: String) {
    def <(in: (Int, T)) = {
      in match {
        case (i, t) =>
          println(s"${t.n} is the ${i} child of ${n}")

      }
    }
  }

  implicit class Param(lower: Int) {
    def apply(t: T) = (lower, t)
  }

but then,

T("foo") < 10 T("bar")

would still fail, but you could work it out with:

T("foo") < 10 (T("bar"))

there isn't a good way of doing what you want without adding parenthesis somewhere.

I think that you might want to go for a combinational parser instead if you really want to stick with this syntax. Or as @korefn proposed, you break the compatibility and do it with new operators.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.