gpt4 book ai didi

存在类型的 Scala 类型推断

转载 作者:行者123 更新时间:2023-12-01 09:37:42 26 4
gpt4 key购买 nike

考虑以下代码片段,它是我原来问题的简化版本:

case class RandomVariable[A](values: List[A])
case class Assignment[A](variable: RandomVariable[A], value: A)

def enumerateAll(vars: List[RandomVariable[_]], evidence: List[Assignment[_]]): Double =
vars match {
case variable :: tail =>
val enumerated = for {value <- variable.values
extendedEvidence = evidence :+ Assignment(variable, value)
} yield enumerateAll(tail, extendedEvidence)
enumerated.sum
case Nil => 1.0
}

Assignment 需要类型 时,variable 被推断为 RandomVariable[_0] 类型的编译时错误失败了任何为什么 value 也没有被推断为具有类型 _0 我试过给出existential type a name 以便通过使用 case (variable: RandomVariable[T forSome {type T}])::tail => 给编译器一个提示,但这也不会编译(说它找不到类型 T,我也有兴趣对其进行解释)。

为了进一步的动机,请考虑我们何时按如下方式捕获类型参数:

case variable :: tail =>
def sum[A](variable: RandomVariable[A]): Double = {
val enumerated = for {value <- variable.values
extendedEvidence = evidence :+ Assignment(variable, value)
} yield enumerateAll(tail, extendedEvidence)
enumerated.sum
}
sum(variable)

此编译没有警告/错误。在第一个示例中我可以修改一些不需要这个额外功能的东西吗?

编辑:更明确地说,我想知道为什么 value 没有被推断为 _0 类型,即使 variable_0 类型,每个值都来自 variable 中的 List[_0]。另外我想知道是否有任何其他方法可以告诉编译器这个事实(除了我上面给出的在函数中捕获类型之外)。

最佳答案

另一种编译解决方案,比使用函数捕获类型更干净(?)。然而,这更令人费解的是,为什么类型推断在原始情况下会失败。

def enumerateAll(vars: List[RandomVariable[_]], evidence: List[SingleAssignment[_]]): Double = vars match {
case (variable@RandomVariable(values)) :: tail =>
val enumeration = for {value <- values
assignment = SingleAssignment(variable, value)
extendedEvidence = evidence :+ assignment
} yield enumerateAll(tail, extendedEvidence)
enumeration.sum
case Nil => 1.0
}

它还会返回以下警告:

scala: match may not be exhaustive.
It would fail on the following input: List((x: questions.RandomVariable[?] forSome x not in questions.RandomVariable[?]))
def enumerateAll(vars: List[RandomVariable[_]], evidence: List[SingleAssignment[_]]): Double = vars match {

截至发帖时我无法破译。此外,使用参数列表中的 int、double 和 string 的 RandomVariable,使用一些测试用例运行它会产生所需的结果,不会出现匹配错误。

关于存在类型的 Scala 类型推断,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14250561/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com