简而言之:我尝试写类似 A <N B
的内容对于 Scala 中的 DSL,对于类型 T 的整数 N 和 A,B。是否有可能这样做?
更长:我尝试为 TGrep2 编写 DSL。在斯卡拉。我目前有兴趣写
A <N B B is the Nth child of A (the rst child is <1).
以一种很好的方式,并尽可能接近 Scala 中的原始定义。有没有办法让<
重载运算符可以将 N 和 B 作为参数。
我尝试过的:我尝试了两种不同的可能性,但这并没有让我很高兴:
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!
和
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!
最佳答案
我建议您使用类似 nth
的内容而不是 <
使语义清晰的符号。 A nth N is B
至少对我来说很有意义。它会翻译成类似的东西
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)
}
}
您可以轻松做到:
val t = T("Mice")
val t1 = T("Rats")
val j = J(List(t1,t))
j nth 1 is t //res = true
关于Scala 运算符重载多个参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15758766/