scala - Returning a path-dependent type -
how can design method returns path dependent type? in following example, deliberately want vertex
path dependent on tree
such forbidden mix vertices across trees (and example):
trait tree { trait vertex def root: vertex def addchild(parent: vertex): vertex } trait treefactory { def make: tree }
now following cannot constructed:
def test(f: treefactory): (tree, map[tree#vertex, tree#vertex]) = { val t = f.make var sq = indexedseq(t.root) var m = map.empty[t.vertex, t.vertex] for( <- 1 100) { val p = sq(util.random.nextint(sq.size)) val c = t.addchild(p) m += c -> p sq :+= c } (t, m) }
because map return should not have keys , values of type tree#vertex
of path dependent vertex...
error: type mismatch; found : scala.collection.immutable.map[t.vertex,t.vertex] required: map[tree#vertex,tree#vertex] note: t.vertex <: tree#vertex, trait map invariant in type a. may wish investigate wildcard type such `_ <: tree#vertex`. (sls 3.2.10) (t, m) ^
if try decouple tree creation , parent-child map build-up:
def test(t: tree): map[t.vertex, t.vertex] = { var sq = indexedseq(t.root) var m = map.empty[t.vertex, t.vertex] (i <- 1 100) { val p = sq(util.random.nextint(sq.size)) val c = t.addchild(p) m += c -> p sq :+= c } m }
this fails reason: "error: illegal dependent method type"
my twisted mind came one. hope there more elegant solution:
trait gagaism { val tree: tree val map: map[tree.vertex, tree.vertex] } def test(f: treefactory) = new gagaism { val tree = f.make val map = { var sq = indexedseq(tree.root) var m = map.empty[tree.vertex, tree.vertex] (i <- 1 100) { val p = sq(util.random.nextint(sq.size)) val c = tree.addchild(p) m += c -> p sq :+= c } m } }
Comments
Post a Comment