Scala - 从 DSL 的应用方法中省略括号
我正在尝试创建 DSL 并遇到问题。我有这些定义:
case class Var(name: String)
case class Lam(v: Var, t: Var)
val (a, b) = (Var("a"), Var("b"))
我希望能够做到这一点:
scala> \ a b
Lam(Var(a),Var(b))
阅读括号删除规则,我发现我需要链接每个接受一个参数的函数,因此我创建了一系列“构建器”类执行构造:
class LamBuilderB(v: Var) {
def apply(t: Var) = Lam(v, t)
}
class LamBuilderA {
def apply(v: Var) = new LamBuilderB(v)
}
val \ = new LamBuilderA
我希望这会起作用,因为每个 apply
仅需要一个参数。但是,对于 apply
来说,删除括号似乎并不合法,因为它希望将参数视为方法名称:
scala> \(a)(b)
res95: Lam = Lam(Var(a),Var(b))
scala> \ a b
error: value a is not a member of LamBuilderA
\ a b
^
有什么想法如何获得没有括号的 DSL 语法吗?
额外问题:我可以得到这个吗?:
scala> \a.b
Lam(Var(a),Var(b))
I'm trying to create a DSL and running into a problem. I have these definitions:
case class Var(name: String)
case class Lam(v: Var, t: Var)
val (a, b) = (Var("a"), Var("b"))
I want to be able to do this:
scala> \ a b
Lam(Var(a),Var(b))
Reading up on the rules of parenthesis dropping, I see that I need to chain functions that take one parameter each, so I've created a series of "builder" classes that perform the construction:
class LamBuilderB(v: Var) {
def apply(t: Var) = Lam(v, t)
}
class LamBuilderA {
def apply(v: Var) = new LamBuilderB(v)
}
val \ = new LamBuilderA
I had hoped this would work since each apply
takes only one argument. But, it doesn't seem like dropping the parentheses is legal for apply
since it wants to treat the argument as a method name:
scala> \(a)(b)
res95: Lam = Lam(Var(a),Var(b))
scala> \ a b
error: value a is not a member of LamBuilderA
\ a b
^
Any ideas how how I can get the DSL syntax without parentheses?
Bonus Question: Can I get this?:
scala> \a.b
Lam(Var(a),Var(b))
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用 4 个一元前缀运算符(
~
、!
、+
、-
)之一可以非常接近:You can get pretty close using one of 4 unary prefix operators (
~
,!
,+
,-
):