Scala 运算符重载多个参数

标签 scala syntax operator-overloading dsl

简而言之:我尝试写类似 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/

相关文章:

mysql - H2提示语法错误,MySQL接受它-但是,语法错误会给出正确的结果: Column … must be in the GROUP BY list;

c++ - 运算符函数是否也会导致函数开销

c++ - 为前后增量重载 C++

C# 中的运算符重载

scala - 高阶函数上的元组模式匹配

scala - Spark 结构化流 未授权访问组

scala - IntelliJ - 远程 Scala 编译服务器

c - 关于函数声明的问题

OSX 上的 Scala SBT/Maven2 错误 : "Error Opening Zip File" -> MissingRequirementError

vim 如何在没有语法高亮的情况下设置好索引?