scala 内联函数 - "ar.reduce((x,y) => x)"有效,但 "ar.reduce{case(x,y) => x}"无效

标签 scala functional-programming

给出以下输入:

scala> val as = List(Array(1,2,3), Array(10,20,30), Array(100,200,300))
as: List[Array[Int]] = List(Array(1, 2, 3), Array(10, 20, 30), Array(100, 200, 300))

我想知道为什么会这样:

示例 1

scala> as.reduce((x,y) => x)
res65: Array[Int] = Array(1, 2, 3)

但是这个看似相同的东西不起作用:

示例 2

scala> as.reduce{case(x,y) => x}
<console>:13: error: missing parameter type for expanded function
The argument types of an anonymous function must be fully known. (SLS 8.5)
Expected type was: (?, ?) => ?
       as.reduce{case(x,y) => x}

任何人都可以解释为什么第一个示例有效但第二个示例无效?

最佳答案

正如错误消息所述,您需要指定类型Array[Int]。这个可以工作:

as.reduce[Array[Int]]{ case (x,y) => x}

有一个很好的解释here .

关于scala 内联函数 - "ar.reduce((x,y) => x)"有效,但 "ar.reduce{case(x,y) => x}"无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42799253/

相关文章:

scala - 如何在 Scala 中编写返回 Option[List] 的函数?

.net - 为什么无限递归不会在F#中遇到堆栈溢出异常?

Scala 高级类型和协变

scala - 为什么阻止 future 被认为是一种不好的做法?

scala - scalaz 中的笛卡尔积遍历

functional-programming - 为什么即使我在 OCaml 中使用了尾递归,我仍然得到 stackoverflow?

php - PHP 是否具有与 Python 的 all() 等效的功能?

javascript - 递归javascript数组长度

scala - apache Spark 模型训练后如何对新训练示例进行分类?

algorithm - 使用归并排序计算反转次数