Rou*_*ari 8 scala infix-operator
我正在研究DSL,我遇到了使用方法作为链中的中缀运算符的问题.我将尝试用一些代码来解释它.我有一个特质Term和案例类Literal并Variable扩展它.我想使用一些运算符构造一个术语实例列表.
case class Expr(val terms: List[Term]) {
def +(v: String) = Expr(Literal(v) :: terms)
def -->(func: List[String] => List[String]) = terms match {
case Literal(v) :: ts => Expr(Variable(v, func) :: ts)
case _ => throw new Exception("Can only apply function on literal")
}
}
object foo {
def bar(name: String) = Expr(Literal(name) :: Nil)
}
// some functions
val one = ...
val all = ...
// works
foo bar "x"
// res1: Expr = Expr(List(Literal(x)))
// works not
foo bar "x" --> all
// error: value --> is not a member of java.lang.String
// works
(foo bar "x") --> all
// res1: Expr = Expr(List(Variable(x,<function1>)))
Run Code Online (Sandbox Code Playgroud)
我希望这相当于foo.bar("x").-->(all)但是翻译似乎也认为是这样foo.bar("x".-->(all)).
ten*_*shi 16
您可以在此处找到运算符优先级:
根据第一个答案,-与字母相比具有更高的优先级.所以编译器组表达式如下:
foo bar ("x" --> all)
Run Code Online (Sandbox Code Playgroud)
如果你将用-->较低优先级的东西(例如字母)替换,那么它应该编译.例如:
foo bar "x" to all
Run Code Online (Sandbox Code Playgroud)
您也可以选择更高优先级的运算符而不是bar.~~>会有类似的事情,因为它~是特殊字符,它具有最高优先级:
foo ~~> "x" --> all
Run Code Online (Sandbox Code Playgroud)