相关疑难解决方法(0)

类型和继承在scalaz中

这是我第二次尝试定义问题,我无法理解它.

我想能够定义一个代数类型并在其上定义一个简单的类型类,比方说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) …

scala scalaz

5
推荐指数
1
解决办法
137
查看次数

Scala:基于类型的列表分区

我有这个代码,我想改进:

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)

我想在以下方面对此进行改进:

  1. 我可以更改其partition返回类型,以便它表明Foo[B]第二个列表中没有吗?
  2. 我可以摆脱Foo类型参数T(即更改Foocase class Foo(a: A) …

types scala shapeless

4
推荐指数
1
解决办法
402
查看次数

标签 统计

scala ×2

scalaz ×1

shapeless ×1

types ×1