是否可以将元素添加到一些应该是异构列表的可变对象?
所以我的意思是,我正在处理 Dijkstra 的算法,我需要以这种方式将一些函数保留在图形的弧中:
class Arc[M, N, T, K](var start: Node[M], var end: Node[N], var f: T => K)
其中start
- 是起始节点;end
- 结束节点;f
- 是节点之间的一些函数,Arc 是保持这个函数的对象,这对我来说是最重要的。
这一切都很完美,但我将所有弧线保存在节点内的列表中:
class Node[T] (s: T) (implicit m: TypeTag[T]) {
var transitions: List[Arc[T, _, _, _]] = Nil
//...
def addArc[M, N, L] (end: Node[M], f: N => L): Arc[T, _, _, _] = {
transitions = new Arc(this, end, f) :: transitions
transitions.head
}
}
你看,问题是我们在简单列表中丢失了类型;在向我们的节点添加新弧时,我们将完全丢失有关类型的所有信息。
解决问题的可能方法是使用HLists
; 一些工作代码的示例(为解释添加更多信息):
// for example we got some type convertion functions
def doubleToInt(x: Double) = x.toInt
def doubleToString(x: Double) = x.toString
def stringToInt(x: String) = x.toInt
def intToDouble(x: Int) = x.toDouble
// and we got some class, with two any args and one function;
class testyfunc[M, N, K, T] (a: M, b: N, c: K => T) {
var f: K => T = c(_)
}
// ok lets build HList
var omglist = HNil
var omglist1 = (new testyfunc (1, "234", intToDouble)) :: omglist
var omglist2 = (new testyfunc (1, "234", doubleToInt)) :: omglist1
var omglist3 = (new testyfunc (1, "234", doubleToString)) :: omglist2
var omglist4 = (new testyfunc (1, "234", stringToInt)) :: omglist3
// it all works!
println(omglist4.head.f("223")) // > 223
// lest check types; yeah it's perfect!
/* shapeless.::[main.scala.Main.testyfunc[Int,java.lang.String,String,Int],
shapeless.::[main.scala.Main.testyfunc[Int,java.lang.String,Double,java.lang.String],
shapeless.::[main.scala.Main.testyfunc[Int,java.lang.String,Double,Int],
shapeless.::[main.scala.Main.testyfunc[Int,java.lang.String,Int,Double],
shapeless.HNil]]]] */
顺便说一句,现在一切都是这样的:
var omglistNH: List[testyfunc[_, _, _, _]] = Nil // here we loose types!
omglistNH = (new testyfunc (1, "234", intToDouble)) :: omglistNH
omglistNH = (new testyfunc (1, "234", doubleToInt)) :: omglistNH
omglistNH = (new testyfunc (1, "234", doubleToString)) :: omglistNH
omglistNH = (new testyfunc (1, "234", stringToInt)) :: omglistNH
println(omglistNH.head.f("223"))
// obviously we got a type error; cause of incorrect types
/* type mismatch;
found : String("223")
required: _$9 where type _$9
println(omglistNH.head.f("223"))
^ */
所以问题是我怎样才能像下面的代码一样制作smth(它是不正确的——类型错误),并将元素添加到这个HList:
var omglist = HNil
omglist = (new testyfunc (1, "234", intToDouble)) :: omglist
omglist = (new testyfunc (1, "234", doubleToInt)) :: omglist
omglist = (new testyfunc (1, "234", doubleToString)) :: omglist
omglist = (new testyfunc (1, "234", stringToInt)) :: omglist
因为我什至不知道如何传递这种类型的不匹配,而且我看不到任何方法可以将所有转换保留为节点的字段并保留所有类型。
编辑
嗯,我可以将转换传递给构造函数,而根本不使用可变对象。