3

我想丰富一个“scala 图表”图表。为此,我创建了一个隐式值类:

import scalax.collection.mutable
import scalax.collection.edge.DiEdge

...
    type Graph = mutable.Graph[Int, DiEdge]
    implicit class EnrichGraph(val G: Graph) extends AnyVal {
        def roots = G.nodes.filter(!_.hasPredecessors)
        ...
    }
...

问题在于其方法的返回类型,例如:

import ....EnrichGraph

val H: Graph = mutable.Graph[Int,DiEdge]()

val roots1 = H.nodes.filter(!_.hasPredecessors)  // type Iterable[H.NodeT]
val roots2 = H.roots        // type Iterable[RichGraph#G.NodeT] !!

val subgraph1 = H.filter(H.having(roots1)) // works!
val subgraph2 = H.filter(H.having(roots2)) // type mismatch! 

原因是否在于“Graph”具有依赖的子类型,例如 NodeT?有没有办法使这种浓缩工作?

4

1 回答 1

4

通常有效的方法是将单例类型作为类型参数传播到EnrichGraph. 这意味着一些额外的样板,因为您必须将implicit classaclass和 an拆分为implicit def.

class EnrichGraph[G <: Graph](val G: G) extends AnyVal {
    def roots: Iterable[G#NodeT] = G.nodes.filter(!_.hasPredecessors)
    //...
}
implicit def EnrichGraph(g: Graph): EnrichGraph[g.type] = new EnrichGraph[g.type](g)

这里的要点是G#NodeT =:= H.NodeT如果G =:= H.type,或者换句话说(H.type)#NodeT =:= H.NodeT。(=:=是类型相等运算符)

你得到那个奇怪类型的原因是它roots有一个依赖于路径类型的类型。并且该路径包含 value G。因此val roots2,您的程序中的类型需要包含 G. 但是由于G绑定到一个没有被任何变量引用的实例EnrichGraph,编译器无法构造这样的路径。编译器可以做的“最好”的事情是构造一个类型,其中省略了路径的那部分:Set[_1.G.NodeT] forSome { val _1: EnrichGraph }. 这是我实际使用您的代码得到的类型;我假设您正在使用以不同方式打印此类型的 Intellij。

正如@DmytroMitin 所指出的,一个可能更适合您的版本是:

import scala.collection.mutable.Set
class EnrichGraph[G <: Graph](val G: G) extends AnyVal {
    def roots: Set[G.NodeT] = G.nodes.filter(!_.hasPredecessors)
    //...
}
implicit def EnrichGraph(g: Graph): EnrichGraph[g.type] = new EnrichGraph[g.type](g)

由于您的其余代码实际上需要 aSet而不是Iterable.

The reason why this still works despite reintroducing the path dependent type is quite tricky. Actually now roots2 will receive the type Set[_1.G.NodeT] forSome { val _1: EnrichGraph[H.type] } which looks pretty complex. But the important part is that this type still contains the knowledge that the G in _1.G.NodeT has type H.type because that information is stored in val _1: EnrichGraph[H.type].

With Set you can't use G#NodeT to give you the simpler type signatures, because G.NodeT is a subtype of G#NodeT and Set is unfortunately invariant. In our usage those type will actually always be equivalent (as I explained above), but the compiler cannot know that.

于 2019-04-19T13:33:26.773 回答