加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

Scala中的中缀运算符的实际优先级

发布时间:2020-12-16 08:49:35 所属栏目:安全 来源:网络整理
导读:2011年5月24日 Scala Language Specification在第7.12.3节中有一个拼写错误,发现于 here.这是邮件列表上的 acknowledged. 中缀运算符的实际优先级是什么? 解决方法 我认为通过测试来计算它会很有趣,我编写了以下代码在REPL中执行.鉴于: val ops = List( "l
2011年5月24日 Scala Language Specification在第7.12.3节中有一个拼写错误,发现于 here.这是邮件列表上的 acknowledged.

中缀运算符的实际优先级是什么?

解决方法

我认为通过测试来计算它会很有趣,我编写了以下代码在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%sn}".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类,运行测试并加载comps

: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
|
^
&
! =?
< >
:?
+ -
* / %
?

所以与规范的主要区别是< >需要切换=!

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读