【问题标题】:Syntax for partial application of curried functions with reverse-associative infix notation使用反向关联中缀表示法部分应用柯里化函数的语法
【发布时间】:2011-10-12 05:39:15
【问题描述】:

换句话说,这有什么不应该编译的充分理由吗?

def f(xs: List[Int]) = xs.foldLeft(0) _  // OK
def f(xs: List[Int]) = (xs :\ 0) _       // OK
def f(xs: List[Int]) = (0 /: xs) _

<console>:15: error: missing arguments for method /: in trait TraversableOnce;
follow this method with `_' if you want to treat it as a partially applied function

以下是一些解决方法:

def f(xs: List[Int]) = xs./:(0) _
def f(xs: List[Int]): ((Int, Int) => Int) => Int = (0 /: xs)

但我的问题主要是关于一般的正确语法。

【问题讨论】:

  • +1,当在表达式def f(xs: List[Int]): (Int, Int) =&gt; Int =&gt; Int = (xs :\ 0)found : (Int, Int) =&gt; Int =&gt; Intrequired: (Int, Int) =&gt; Int =&gt; Int中省略一对括号时,我发现了另一个令人困惑的编译器错误

标签: scala currying infix-notation partial-application associativity


【解决方案1】:

我刚刚修复了这个问题,但我还不能签入,因为它需要修改规范。

scala> def f(xs: List[Int]) = (0 /: xs) _
f: (xs: List[Int])(Int, Int) => Int => Int

scala> f(1 to 10 toList)
res0: (Int, Int) => Int => Int = <function1>

scala> res0(_ + _)
res1: Int = 55

问题在于,如果 op 是右关联的,则规范将“e1 op e2”定义为 { val x=e1; e2.op(x) } 原因对我来说并不明显,因为更简单的 e2.op(e1) 解决了这个问题,比如https://issues.scala-lang.org/browse/SI-1980。我会查询的。

【讨论】:

  • 不,不要屏住呼吸。影响太大了。
【解决方案2】:

看起来像一个编译器错误。我已经在不同的 scala 版本上测试了这个表达式以及我得到了什么:

def f(xs: List[Int]) = (0 /: xs) _

2.9.1.final2.8.2.final 的行为相同,但 2.7.7.final 会触发不同的错误消息(IterableTraversableOnes),但我认为这是因为旧版本中重新设计了集合库。

def f(xs: List[Int]) = (0 /: xs) _
<console>:4: error: missing arguments for method /: in trait Iterable;
follow this method with `_' if you want to treat it as a partially applied function

我在评论中提到的表达式对于不同的 scala 版本表现不同。

def f(xs: List[Int]): (Int, Int) => Int => Int = (0 /: xs)

scala 2.9.1.final:

 found   : (Int, Int) => Int => Int
 required: (Int, Int) => Int => Int

真正令人困惑的编译器消息,绝对是一个错误。

scala 2.8.2.final:

 found   : => ((Int, Int) => Int) => Int
 required: (Int, Int) => (Int) => Int

一开始很奇怪的=&gt;,与2.7.7相比。最终结果看起来像是回归。

scala 2.7.7.final:

 found   : ((Int, Int) => Int) => Int
 required: (Int, Int) => (Int) => Int

found 看似正确,但代码仍然无法正常工作。

我在scala bugtracker 上搜索过类似的问题,但找不到合适的东西。认为创建一张票就足够了(或两张?看起来这两个错误无关)。

【讨论】:

猜你喜欢
  • 2012-03-14
  • 2012-12-27
  • 1970-01-01
  • 2014-06-11
  • 1970-01-01
  • 2011-08-18
  • 1970-01-01
  • 1970-01-01
  • 2022-08-14
相关资源
最近更新 更多