在类型参数上创建 Show 实例?
Creating a Show instance on a type parameter?
我正在通过 Scala with Cats 工作,我正在尝试在 Tree[A]
类型上创建一个 Show
(不是书本练习)。基本上,我试图创建一个实例,如果我有任何树,其基础值有一个 Show
实例,我可以调用 tree.show
。我正在为如何表示这一点而苦苦挣扎。
到目前为止,我有
sealed trait Tree[+A]
final case class Branch[A](left: Tree[A], right: Tree[A]) extends Tree[A]
final case class Leaf[A](value: A) extends Tree[A]
object Tree {
implicit val show: Show[Tree[Show[_]]] = new Show[Tree[Show[_]]] {
def show(t: Tree[Show[_]]): String = t match {
case Branch(left, right) => s"*\n/\n${show(left)} ${show(right)}\n"
case Leaf(value) => value.show
}
}
}
我得到missing argument list for method show in trait ContravariantShow
Unapplied methods are only converted to functions when a function type is expected.
You can make this conversion explicit by writing show _ or show(_) instead of
显示.
当我重写为value.show(_)
时,我得到了type mismatch; found : _ => String required: String
当我只写了一个字符串 "value"
来测试时,我的 Tree[Int]
实例无法在类型 Tree[Int]
.[=23= 上找到方法 show
]
关于如何使这项工作有任何想法吗?
Basically, I am trying to create an instance such that if I have any tree whose underlying values have a Show instance.
这就是您问题的答案。
只要您知道 A
有一个 Show,您就可以为 Tree[A]
导出一个 Show。
object Tree {
implicit def treeShow[A](implicit aShow: Show[A]): Show[Tree[A]] =
new Show[Tree[A]] {
override def show(t: Tree[A]): String = t match {
case Branch(left, right) => s"*\n/\n${show(left)} ${show(right)}\n"
case Leaf(value) => aShow.show(value)
}
}
}
我正在通过 Scala with Cats 工作,我正在尝试在 Tree[A]
类型上创建一个 Show
(不是书本练习)。基本上,我试图创建一个实例,如果我有任何树,其基础值有一个 Show
实例,我可以调用 tree.show
。我正在为如何表示这一点而苦苦挣扎。
到目前为止,我有
sealed trait Tree[+A]
final case class Branch[A](left: Tree[A], right: Tree[A]) extends Tree[A]
final case class Leaf[A](value: A) extends Tree[A]
object Tree {
implicit val show: Show[Tree[Show[_]]] = new Show[Tree[Show[_]]] {
def show(t: Tree[Show[_]]): String = t match {
case Branch(left, right) => s"*\n/\n${show(left)} ${show(right)}\n"
case Leaf(value) => value.show
}
}
}
我得到missing argument list for method show in trait ContravariantShow
Unapplied methods are only converted to functions when a function type is expected.
You can make this conversion explicit by writing show _ or show(_) instead of
显示.
当我重写为value.show(_)
时,我得到了type mismatch; found : _ => String required: String
当我只写了一个字符串 "value"
来测试时,我的 Tree[Int]
实例无法在类型 Tree[Int]
.[=23= 上找到方法 show
]
关于如何使这项工作有任何想法吗?
Basically, I am trying to create an instance such that if I have any tree whose underlying values have a Show instance.
这就是您问题的答案。
只要您知道 A
有一个 Show,您就可以为 Tree[A]
导出一个 Show。
object Tree {
implicit def treeShow[A](implicit aShow: Show[A]): Show[Tree[A]] =
new Show[Tree[A]] {
override def show(t: Tree[A]): String = t match {
case Branch(left, right) => s"*\n/\n${show(left)} ${show(right)}\n"
case Leaf(value) => aShow.show(value)
}
}
}