优先级队列scala中无类型
我使用优先级队列来排序一个名为TreeNodeWithCostAndHeuristic的案例类优先级队列scala中无类型,scala,functional-programming,Scala,Functional Programming,我使用优先级队列来排序一个名为TreeNodeWithCostAndHeuristic的案例类 case class TreeNodeWithCostAndHeuristic[S,A](parent:Option[TreeNodeWithCostAndHeuristic[S,A]], action: Option[A],
case class TreeNodeWithCostAndHeuristic[S,A](parent:Option[TreeNodeWithCostAndHeuristic[S,A]],
action: Option[A],
state: S,
cost: Double,
estimatedRemainingCost: Double)
此优先级队列是在函数内创建的,该函数使用其参数设置初始状态,而其他值必须保持为None或0
def HeuristicGraphSearch[S,A](problem: ProblemWithCostAndHeuristic[S,A]) = {
val root = TreeNodeWithCostAndHeuristic(parent = None,action=None,state=problem.initialState,cost = 0.0, estimatedRemainingCost = 0.0)
val frontier : mutable.PriorityQueue[TreeNodeWithCostAndHeuristic[S,A]] = mutable.PriorityQueue.empty[TreeNodeWithCostAndHeuristic[S,A]]
frontier.enqueue(root)
但是,由于父项和操作均为none,因此预期类型TreeNodeWithCostAndHeuristic[S,a]
与我尝试排队的类型TreeNodeWithCostAndHeuristic[S,Nothing]
之间不匹配
据我所知,Nothing是Option的子类型,在我的示例类中,parent和action都是Option。为什么会出现不匹配?这与Scala编译器推断类型的方式有关。简单的回答是,在构建case类时,通过显式声明类型来帮助解决这个问题:
val root = TreeNodeWithCostAndHeuristic[S, A](parent = None,action=None,state=problem.initialState,cost = 0.0, estimatedRemainingCost = 0.0)
TreeNodeWithCostAndHeuristic[S,Nothing]
被认为不是TreeNodeWithCostAndHeuristic[S,a]
的有效替代品,原因在于它不是它的子类;如果某个Foo[A]
在其类型A
中是协变的,那么只有以下情况成立:Foo[S]除了sloucs-answer之外,您还可以使用它来帮助编译器:
val root = TreeNodeWithCostAndHeuristic(
parent = None: Option[TreeNodeWithCostAndHeuristic[S, A]],
action = None: Option[A],
state = problem.initialState,
cost = 0.0,
estimatedRemainingCost = 0.0)
编译器抱怨的原因是它无法保证无。type
是一个选项[TreeNodeWithCostAndHeuristic[S,a]]
和选项[a]
,因此它“退出”并推断无任何内容,这是所有类型的底部类型
@Dima还建议使用选项。空[A]
:
val root = TreeNodeWithCostAndHeuristic(
parent = Option.empty,
action = Option.empty[A],
state = problem.initialState,
cost = 0.0,
estimatedRemainingCost = 0.0)
我宁愿使用选项。empty
-看起来比这里的类型归属要好一点:action=Option.empty[a]
@Dima您可能是对的,我不确定我更喜欢哪一个。我将两者都加上。