这是我第二次尝试定义问题,我无法理解它.
我想能够定义一个代数类型并在其上定义一个简单的类型类,比方说Show.在哈斯克尔我做:
data Tree a = EmptyTree | Node a deriving (Show)
Run Code Online (Sandbox Code Playgroud)
现在,如果我输入EmptyTree- haskell可以显示它,所以它属于Show.
现在我想在scala中做同样的事情:
sealed abstract class Tree[+T]
case object EmptyTree extends Tree[Nothing]
case class Node[T](value: T) extends Tree[T]
Run Code Online (Sandbox Code Playgroud)
然后我定义Show它:
implicit def show[T] = Show.showA[Tree[T]]
Run Code Online (Sandbox Code Playgroud)
我能做到println((EmptyTree : Tree[Int]).show).但我做不到println(EmptyTree.show)(回应是value show is not a member of object EmptyTree)
我必须写更多:
implicit class MyShowOps[A, +T <: Tree[A]](t: T) {
def showMy(implicit ev: Show[Tree[A]]): String = ev.shows(t)
}
Run Code Online (Sandbox Code Playgroud)
只有这样我才能做到 println(EmptyTree.showMy) …
我有这个代码,我想改进:
sealed abstract class A
case class B() extends A
case class C() extends A
case class D() extends A
case class Foo[+T <: A](a: T)
/** Puts instances that match Foo(B()) in the first list and everything else,
* i.e. Foo(C()) and Foo(D()), in the second list. */
def partition(foos: List[Foo[_ <: A]]): (List[Foo[B]], List[Foo[_ <: A]]) = {
// ...
}
Run Code Online (Sandbox Code Playgroud)
我想在以下方面对此进行改进:
partition返回类型,以便它表明Foo[B]第二个列表中没有吗?Foo类型参数T(即更改Foo为case class Foo(a: A) …