上下文绑定了更高的kinded类型?

时间:2016-02-10 02:11:46

标签: scala higher-kinded-types

我想做这样的事情:

def fold[C[A]](implicit ev: Foldable[A]): A

我正在not found: type A

我知道,我可以这样做:

def fold[C[_], A: Foldable]: A

但是,我宁愿调用fold[List[Int]]而不是fold[List, Int]

2 个答案:

答案 0 :(得分:1)

以下是我提出的建议:

trait Foo[T, A]

implicit def makeFoo[A, M[_]] = new Foo[M[A], A] {}

class Helper[T] {
  def apply[A]()(implicit ev: Foo[T, A]) = ev 
}

def bar[T] = new Helper[T]

bar[List[Int]]()
//Foo[List[Int],Int] = $anon$1@7edf6563

如果你真的想要一个无法参与的方法,空的一对parens可能并不理想,但我现在看不到如何解决这个问题。

答案 1 :(得分:1)

我玩了一下它并提出了一个帮助类型类:

trait Helper[M[_], CA] {
  type C[_]
  type A
  implicit def ma: M[A]
}
object Helper {
  implicit def instance[M0[_], C0[_], A0](implicit ma0: M0[A0]) = new Helper[M0, C0[A0]] {
    type C[X] = C0[X]
    type A = A0
    val ma: M0[A0] = ma0
  }
}

我知道名字非常通用,我建议找到更有意义的名字。

现在,您需要隐式的Foldable[A]而不是隐含的Helper[Foldable, CA],其中CA是您示例中必须与List[Int]匹配的类型:< / p>

def fold[CA](implicit helper: Helper[Foldable, CA]): helper.A

举个例子:

def fold[CA](implicit helper: Helper[Foldable, CA]): helper.A = {
  import helper._
  println(implicitly[Foldable[A]])
  null.asInstanceOf[A]
}

scala> :paste
// Entering paste mode (ctrl-D to finish)
case class Foldable[A](name: String)
implicit val stringFoldable = Foldable[String]("String")
implicit val intFoldable = Foldable[Int]("Int")
implicit val floatFoldable = Foldable[Float]("Float")

def fold[CA](implicit helper: Helper[Foldable, CA]): helper.A = {
  import helper._
  println(implicitly[Foldable[A]])
  null.asInstanceOf[A]
}
// Exiting paste mode, now interpreting.

defined class Foldable
stringFoldable: Foldable[String] = Foldable(String)
intFoldable: Foldable[Int] = Foldable(Int)
floatFoldable: Foldable[Float] = Foldable(Float)
fold: [CA](implicit helper: Helper[Foldable,CA])helper.A

scala> fold[List[String]]
Foldable(String)
res0: String = null

scala> fold[List[Int]]
Foldable(Int)
res1: Int = 0

scala> fold[List[Float]]
Foldable(Float)
res2: Float = 0.0
相关问题