1

以下是我在 scala 中的方法签名和定义

  def accumulate[T[_]: Traversable, O: Monoid, A]: (A => O) => T[A] => O =
    fao => ta =>
      (implicitly[Traversable[T]].traverse[({type f[X] = Acc[O, X]})#f, A, O](ta)(a => Acc(fao(a)))).value

  def reduce[T[_]: Traversable, O: Monoid]: T[O] => O = to => accumulate[T, O, O](a => a)(to)

但是,对于 reduce 的定义,我收到以下错误

Error:(160, 82) not enough arguments for method accumulate: (implicit evidence$7: Traversable[T], implicit evidence$8: Monoid[O])(O => O) => (T[O] => O).
Unspecified value parameter evidence$8.
  def reduce[T[_]: Traversable, O: Monoid]: T[O] => O = to => accumulate[T, O, O](a => a)(to)
                                                                                 ^

不知道我哪里出错了。任何帮助,将不胜感激。

谢谢!

4

1 回答 1

2

您被该accumulate方法的隐藏(隐式)参数绊倒了。您在其上放置的上下文边界意味着该方法确实具有以下类型签名:

def accumulate[T[_], O, A](
  implicit traversable: Traversable[T],
  monoid: Monoid[O]): (A => O) => T[A] => O

事实上,如果您确实需要在您的方法中使用它们相应的隐式(而不是仅仅将它们隐式传递给另一个方法),我建议您不要使用上下文边界。显式(具有讽刺意味地)输入隐式要清楚得多。

所以,发生的事情reduce是你试图在编译器期望和的两个隐式参数的a => a位置传入函数。解决方案是显式传入隐式,或者在调用它之前进行单态化:Traversable[T]Monoid[O] accumulate

def reduce[T[_]: Traversable, O: Monoid]: T[O] => O = { to =>
  // This forces the compiler to pass in the correct implicits
  val accumulate_ = accumulate[T, O, O]
  accumulate_(a => a)(to)
}
于 2016-10-22T20:02:45.140 回答