【问题标题】:Type mismatch error with foldLeft method in ScalaScala中foldLeft方法的类型不匹配错误
【发布时间】:2014-06-04 18:42:40
【问题描述】:

我有一个在 Scala 中使用 foldLeft 的方法。

def bitSetToByte(b:collection.BitSet, sh:Int=0) = 
  ((0 /: b) {(acc, input) => acc + (1 << (input - sh))}).toByte

该方法有两个用于匿名函数的参数,因此我通过删除形式参数将其替换为 _。

def bitSetToByte(b:collection.BitSet, sh:Int=0) = ((0 /: b) {(_ + (1 << (_ - sh))}).toByte

问题是我有类型不匹配的错误消息。

可能出了什么问题?

【问题讨论】:

  • 作为一个风格问题,为什么你更喜欢/: 而不是fold...
  • @Kevin Meredith:对我来说,它在视觉上更有吸引力,它让我想起了倒在左侧的多米诺骨牌:(START_VALUE) -> /:::::

标签: scala types foldleft


【解决方案1】:

在解释_ 时,编译器假定_ 对应的匿名函数包含在最近的括号中((_) 除外)。基本上,编译器将(_ - sh) 解释为(x =&gt; x - sh),然后抱怨因为您将函数传递给&lt;&lt;,而它需要Int

【讨论】:

    【解决方案2】:

    Frist,你搞砸了括号。我猜你的意思是这样的(为了简洁起见,我也删除了toByte

    def bitSetToByte(b:collection.BitSet, sh:Int) = 
      (0 /: b) { (_ + (1 << (_ - sh))) }
    

    其次,typer 是你的朋友,你可以通过运行带有-Xprint:typer flag 的 scala 解释器来了解你的代码在编译器的 typer 阶段之后的表现

    def bitSetToByte(b: scala.collection.BitSet, sh: Int): Int = {
      <synthetic> <artifact> val x$1: Int = 0;
      b./:[Int](x$1)(((<x$2: error>: <error>) => <x$2: error>.<$plus: error>(1.$less$less(((x$3) => x$3.$minus(sh))))))
    }
    

    lambda 表达式可以简化为

    { x2 => x2 + (1 << (x3 => x3 - sh)) }
    

    这不是你想要的

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-02-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-06
      • 1970-01-01
      相关资源
      最近更新 更多