【发布时间】:2016-03-03 11:02:03
【问题描述】:
考虑下面这段代码:(需要解决的实际代码见下文)
def applyAll[T,S, U <: Seq[T => S]](l : U, x: T) = l.map(f => f(x))
val u = List((i: Int) => i + 1, (i: Int) => i + 2)
println(applyAll(u,1))
(给定 Seq 或 T => S 和一个值,我们希望得到应用于此值的函数)。
虽然applyAll 可以正常编译,但在u 上调用它会出现以下错误:
Error:(35, 13) inferred type arguments [Int,Nothing,List[Int => Int]] do not conform to method applyAll's type parameter bounds [T,S,U <: Seq[T => S]]
println(applyAll(u,1))
^
这表明编译器无法推断类型参数S,我猜这是因为它“嵌套”在函数类型T => S中。
编辑:
我尝试修复的实际代码类似(尽管很复杂),并且无法通过删除 U 参数来修复。这里是:
def applyNatural[T, S, Repr <: TraversableLike[T => S, Repr], That]
(data: T, jobs: Repr)
(implicit bf: CanBuildFrom[Repr, S, That]): That = {
jobs.map(f => f(data))
}
val u = List((i: Int) => i + 1, (i: Int) => i + 2)
val v = applyNatural(1, u)
println(v)
【问题讨论】:
-
我发现编辑代码有两个问题:首先,Repr 是循环的。要解析Repr,您必须查找Repr。其次,没有构建源。
-
你到底想做什么?
-
我正在寻找一个函数,它可以将一组函数应用于一个值,并返回一组相同类型的值。
-
所以输入是函数的集合和 T 类型的值,它应该返回 T 的集合?
标签: scala generics types type-inference