【问题标题】:Scala infix notationScala中缀表示法
【发布时间】:2016-11-29 14:22:24
【问题描述】:

这是我的代码...

val strings: Enumerator[String] = Enumerator("1","2","3","4")

//create am Enumeratee using the map method on Enumeratee

val toInt: Enumeratee[String,Int] = Enumeratee.map[String]{ 
    (s: String) => s.toInt 
}
val toSelf: Enumeratee[String,String] = Enumeratee.map[String]{ 
    (s: String) => s 
}
List("Mary", "Paul") map (_.toUpperCase) filter (_.length > 5)

val r1 = strings |>> (toSelf &>> (toInt &>> sum))
val r2 = strings |>> toSelf &>> (toInt &>> sum)
val r3 = strings |>> toSelf &>> toInt &>> sum // does not compile

val foo1 = strings &> toInt |>> sum
val foo2 = strings &> (toInt |>> sum) // does not compile
val foo3 = (strings &> toInt) |>> sum

符号|>>、&>>。 &> 是方法。我对编译器在它们周围加上括号的方式感到困惑。行内:

List("Mary", "Paul") map (_.toUpperCase) filter (_.length > 5)

编译器像这样插入括号:

((List("Mary", "Paul") map (_.toUpperCase))) filter (_.length > 5)

实际上它编译为:

List("Mary", "Paul").map(((x$3: String) => x$3.toUpperCase()))(List.canBuildFrom[String]).filter(((x$4: String) => x$4.length().>(5)))

在后面的例子中:

strings |>> toSelf &>> (toInt &>> sum)

编译器像这样插入括号:

strings |>> (toSelf &>> (toInt &>> sum))

实际上它编译为:

strings.|>> (toSelf.&>> (toInt.&>>(sum)))

有时编译器似乎是从右到左插入括号(第二个示例),而有时编译器似乎是从左到右插入括号(第一个示例)。有时,就像在

val r3 = strings |>> toSelf &>> toInt &>> sum

我希望它像这样插入括号

val r3 = strings |>> (toSelf &>> (toInt &>> sum))

我得到一个编译器错误。

有人可以解释一下空格分隔方法的括号插入规则吗?

【问题讨论】:

    标签: scala infix-notation


    【解决方案1】:

    infix notation have a precedence 中的操作定义给它们,如规范中所述:

    中缀运算符的优先级由运算符的 第一个字符。以下字符按升序排列 优先级,同一行上的字符具有相同的 优先级:

    (all letters)
    |
    ^
    &
    = !
    < >
    :
    + -
    * / %
    (all other special characters)
    

    运算符的优先级和关联性决定了分组 表达式的一部分如下。

    • 如果一个表达式中有多个中缀操作,那么操作符 具有较高优先级的运算符比具有较低优先级的运算符绑定得更紧密 优先级。

    • 如果有连续的中缀操作 e0; op1; e1; op2… opn; en 与运营商 op1,…,opnop1,…,opn 的优先级相同,然后是所有这些运算符 必须具有相同的关联性。如果所有运营商都是 左结合,序列被解释为 (…(e0;op1;e1);op2…);opn;en。否则,如果 所有运算符都是右结合的,序列被解释为 e0;op1;(e1;op2;(…opn;en)…).

    • 后缀运算符的优先级始终低于中缀运算符。例如。 e1; op1; e2; op2 总是等价于 (e1;op1;e2);op2

    根据规范,您的第二个表达式应该是:

    strings.|>>((toSelf.&>>toInt).&>>(sum)))
    

    由于| 的优先级低于&amp;,因此最后调用它,然后&amp;&gt;&gt; 是左关联的,因此它们从左到右调用。

    【讨论】:

    • 方法&amp;&gt;&gt;的优先级高于|&gt;&gt;,并且&amp;&gt;&gt;是左关联的,所以strings |&gt;&gt; toSelf &amp;&gt;&gt; toInt &amp;&gt;&gt; sum被解释为strings |&gt;&gt; ((toSelf &amp;&gt;&gt; toInt) &amp;&gt;&gt; sum)
    • @JohnReed 是的,这就是我的意思。看来我把括号搞砸了。固定。
    猜你喜欢
    • 2019-02-08
    • 1970-01-01
    • 1970-01-01
    • 2011-08-01
    • 2011-09-23
    • 2011-05-27
    • 1970-01-01
    • 1970-01-01
    • 2016-11-04
    相关资源
    最近更新 更多