【问题标题】:Why does my implementation of Haskell snd not compile in Scala?为什么我的 Haskell snd 实现不能在 Scala 中编译?
【发布时间】:2018-12-30 08:43:08
【问题描述】:

我按照 Haskell snd 的思路定义了以下函数

def snd[T](pair: (_, T)): T = pair._2

尝试将它与 List[ListNode[T]] 一起使用不会编译。为什么不呢?

list
  .reduceOption(snd)

地点:

case class ListNode[T](data: T, var next: Option[ListNode[T]])(implicit ordering: Ordering[T]) extends Ordered[ListNode[T]] {...}

错误:

Type mismatch, expected: (NonInferedA1, NonInferedA1) => NonInferedA1, actual Tuple2[_, Nothing] => Nothing

【问题讨论】:

  • 什么是Node
  • @AndreyTyukin 更新了问题,但不知道这有什么关系。
  • 我认为它需要一个有两个参数的函数,而不是一对?
  • 确实,ListNode 的定义并不重要...您可以构造List.empty[Int],从而省略任何提及NodeNodeList... 无论如何: reduceOption 需要两个参数的函数。 snd 只接受一个参数。
  • 它可以与def twoArgSnd[T](a: Any, b: T): T = breduceOption(twoArgSnd[Int]) 一起正常工作。

标签: scala tuples arity


【解决方案1】:

方法 reducereduceOption 需要具有 2 的元数的函数,而不是采用元组的一元函数。

有区别

Function1[(X, Y), Z]

Function2[X, Y, Z]

第一个是一元的,接受一个元组,第二个是二元的。方法及其 eta 扩展也是如此。

这里按预期工作:

def twoArgSnd[T](a: Any, b: T): T = b 

list.reduceOption(twoArgSnd[Int])

也相关:

  1. Why is scala.collection.immutable.List[Object] not GenTraversableOnce[?]

【讨论】:

猜你喜欢
  • 2021-04-26
  • 2013-09-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多