考虑下面的代码:(见下文,需要解决的实际代码)与函数类型Scala的类型推断
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))
(给出的T => S
一个Seq
和价值,我们期望得到funtions应用于此值)。
虽然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。其次,没有建立。 –
你究竟想要做什么? –
我正在创建一个函数,它可以将一个函数集合应用到一个值,并返回一个相同类型的值的集合。 –