[英]Context bound for higher kinded types?
I want to do something like this: 我想做这样的事情:
def fold[C[A]](implicit ev: Foldable[A]): A
I am getting not found: type A
我not found: type A
I know, I can do this instead: 我知道,我可以这样做:
def fold[C[_], A: Foldable]: A
But, I would rather invoke as fold[List[Int]]
than fold[List, Int]
但是,我宁愿将其作为fold[List[Int]]
不是fold[List, Int]
Here's what I came up with: 这是我想出的:
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
The empty pair of parens might not be ideal if you really want an a no-arg method, but I can't see how to get around that at the moment. 如果您真的想要一个无参数的方法,那么空对括号可能不是理想的选择,但是我目前无法解决该问题。
I played a bit with it and came up with a helper type class: 我玩了一点,并提出了一个辅助类型类:
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
}
}
I know the names are pretty generic, I'd suggest finding more meaningful names. 我知道名称非常通用,建议您找到更有意义的名称。
Now instead of requiring an implicit of type Foldable[A]
you require instead an implicit of Helper[Foldable, CA]
where CA
is the type that must match against List[Int]
in your example: 现在,您不再需要Foldable[A]
类型的隐式,而是需要Helper[Foldable, CA]
的隐式,其中CA
是您的示例中必须与List[Int]
相匹配的类型:
def fold[CA](implicit helper: Helper[Foldable, CA]): helper.A
As an example: 举个例子:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.