Consider the following code snippet, which is a reduced version of my original problem:
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
}
This fails with the compile-time error that variable
was inferred to have type RandomVariable[_0]
when Assignment
required type Any
. Why is value
not also inferred to have type _0
? I tried giving the existential type a name in order to give a hint to the compiler by using case (variable: RandomVariable[T forSome {type T}]) :: tail =>
but that also would not compile (saying it could not find type T, which I'd be interested in an explanation for as well).
For further motivation, consider when we capture the type parameter as follows:
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)
This compiles without warnings/errors. Is there something I can modify in the first example to not require this extra function?
EDIT: To be more explicit, I want to know why value
is not inferred to be of type _0
even though variable
is of type _0
and every value comes from a List[_0]
in variable
. Also I would like to know if there are any additional ways to tell the compiler of this fact (aside from capturing the type in a function as I gave above).