有关scala编译器语法黑客的问题

时间:2009-09-22 19:25:59

标签: scala

我希望编写一个允许如下语法的系统:

a b/c

作为一个类,b是一个特定的术语(不是任意字符串),c是一个Int。

我意识到你可以做到

a b c 

成为

a.b(c)

但是,第一种语法会更优雅,任何解决方案都可以帮助我扩展我的scala知识:)

1 个答案:

答案 0 :(得分:3)

如果其中任何一个对你来说足够好......

a { b/c }
a ( b/c )

......这样就可以了:

trait Term { def / (n:Int):(Term,Int) = (this,n) }

case object Inc extends Term  // any other terms declared likewise

然后你的班级可以这样支持:

class A { 
   def apply(t:(Term,Int)) = t match { 
     case (Inc,n) => n + 1 
     // further term implementations
   } 
}

用法:

scala> val a = new A
a: A = A@1c2628

scala> a { Inc / 8 }
res28: Int = 9

scala> a ( Inc / 8 )
res29: Int = 9