Фактический приоритет для инфиксных операторов в Scala

Спецификация языка Scala от 24 мая 2011 г. содержит опечатку в разделе 6.12.3. Это было подтверждено в списке рассылки.

Каков фактический приоритет для инфиксных операторов?

1 ответ

Решение

Я подумал, что было бы интересно выяснить это, протестировав его. Я написал следующий код для выполнения в REPL. Дано:

val ops = List(
  "letter", "|", "^", 
  "&", "<", ">", "!", 
  "+", "-", "*", "/", "%", "?", 
  "=?", // add ? to prevent assignment
  ":?"  // add ? to prevent right-association
)

Сначала создайте промежуточный файл scala, в котором используются и тестируются операторы.

import java.io._

// generate a class with all ops operators defined
// where operator combines in a way we can figure out the precedence
val methods = ops.map("""def %s(o: Op) = Op("["+o.v+v+"]")""".format(_))
val body = methods.mkString("\n")
val out = new PrintWriter(new FileWriter("Op.scala"))
out.println("case class Op(v: String) {\n%s\n}".format(body))

// generate tests for all combinations and store in comps
// Op(".") op1 Op(".") op2 Op(".") v returns "[[..].]" when op2 > op1
// returns "[.[..]]" when op1 <= op2
def test(op1: String, op2:String) = {
  """("%s","%s") -> (Op(".") %s Op(".") %s Op(".")).v.startsWith("[[")""".
    format(op1, op2, op1, op2)
}
val tests = for (op1 <- ops; op2 <- ops) yield { test(op1, op2) }
out.println("val comps = Map[(String, String), Boolean](%s)".format(
  tests.mkString(",\n")))
out.close

Затем загрузите класс Op, запустите тесты и загрузите компы

:load Op.scala

// order operators based on tests
val order = ops.sortWith((x,y) => comps(x -> y))

// if op1 or op2 don't have higher precedence, they have the same precedence
def samePrecedence(op1: String, op2: String) = 
  !comps(op1 -> op2) && !comps(op2 -> op1)

def printPrecedenceGroups(list: List[String]): Unit = {
  if (list != Nil) {
    val (same, rest) = list.span(op => samePrecedence(op, list.head))
    println(same.mkString(" "))
    printPrecedenceGroups(rest)
  }
}

printPrecedenceGroups(order)

Это печатает:

letter
|
^
&
! =?
< >
:?
+ -
* / %
?

Таким образом, основное отличие от спецификации < > должен быть переключен с = !,

Другие вопросы по тегам