在阅读关于this excellent intro的matryoshka后,我尝试将IntList
转换为通用列表(我在下面的示例中保留了名称IntList
)
sealed trait IntList[+H, +A]
case class Cons[A](head: H, tail: A) extends IntList[H, A]
case object Empty extends IntList[Nothing, Nothing]
implicit def intListFunct[H]: Functor[IntList[H, ?]] = new Functor[IntList[H, ?]] {
def map[A, B](fa: IntList[H, A])(f: A => B): IntList[H, B] = fa match {
case Cons(head, tail) => Cons(head, f(tail))
case Empty => Empty
}
}
def lst[T](implicit T: Corecursive.Aux[T, IntList[Int, ?]]): T =
Cons(
1,
Cons(
2,
Cons(
3,
Empty.embed
).embed
).embed
).embed
def sumList[T](l: T)(implicit T: Recursive.Aux[T, IntList[Int, ?]]): Int = l.cata[Int] {
case Cons(head, tail) => head + tail
case Empty => 0
}
val listRes = sumList(lst[Fix[IntList[Int, ?]]])
但它没有编译我得到这个错误:
[error] /Users/caente1/workshop/graphs/src/main/scala/graph.scala:40: could not find implicit value for parameter T: matryoshka.Corecursive.Aux[matryoshka.data.Fix[[β$4$]common.lists.package.IntList[Int,β$4$]],[β$2$]common.lists.package.IntList[Int,β$2$]]
[error] val listRes = sumList(lst[Fix[IntList[Int, ?]]])
所以我显然做错了什么,但是我无法理解它,还有什么更好的方法呢?