使用 .toSet 制作的 Set 上的类型推断失败? [英] Type inference fails on Set made with .toSet?

查看:28
本文介绍了使用 .toSet 制作的 Set 上的类型推断失败?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么类型推断在这里失败?

Why is type inference failing here?

scala> val xs = List(1, 2, 3, 3)
xs: List[Int] = List(1, 2, 3, 3)

scala> xs.toSet map(_*2)
<console>:9: error: missing parameter type for expanded function ((x$1) => x$1.$times(2))
       xs.toSet map(_*2)

然而,如果 xs.toSet 被赋值,它会编译.

However, if xs.toSet is assigned, it compiles.

scala> xs.toSet
res42: scala.collection.immutable.Set[Int] = Set(1, 2, 3)

scala> res42 map (_*2)
res43: scala.collection.immutable.Set[Int] = Set(2, 4, 6)

另外,反过来,从List转换为SetList上的映射也符合.

Also, going the other way, converting to Set from List, and mapping on List complies.

scala> Set(5, 6, 7)
res44: scala.collection.immutable.Set[Int] = Set(5, 6, 7)

scala> res44.toList map(_*2)
res45: List[Int] = List(10, 12, 14)

推荐答案

我同意推断唯一可能"的类型会很好,即使调用是链接的,但存在技术限制.

I agree it would be nice to infer "the only possible" type, even when calls are chained, but there are technical limitations.

您可以将推理视为对表达式的广度优先扫描,收集类型变量上的约束(由子类型边界和所需的隐式参数产生),然后解决这些约束.这种方法允许,例如,隐式来指导类型推断.在您的示例中,即使您只查看 xs.toSet 子表达式有一个单一的解决方案,但稍后的链式调用可能会引入使系统无法满足的约束.不解决类型变量的缺点是闭包的类型推断需要知道目标类型,因此会失败(它需要一些具体的东西继续下去——所需的闭包类型和它的参数类型必须不是两者都是未知的).

You can think of inference as a breadth-first sweep over the expression, collecting constraints (which arise from subtype bounds and required implicit arguments) on type variables, followed by solving those constraints. This approach allows, e.g., implicits to guide type inference. In your example, even though there is a single solution if you only look at the xs.toSet subexpression, later chained calls could introduce constraints that make the system unsatisfiable. The downside of leaving the type variables unsolved is that type inference for closures requires the target type to be known, and will thus fail (it needs something concrete to go on -- the required type of the closure and the type of its argument types must not both be unknown).

现在,当延迟求解约束导致推理失败时,我们可以回溯,求解所有类型变量,然后重试,但这很难实现(而且可能效率很低).

Now, when delaying solving the constraints makes inference fail, we could backtrack, solve all the type variables, and retry, but this is tricky to implement (and probably quite inefficient).

这篇关于使用 .toSet 制作的 Set 上的类型推断失败?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆