Ulysse Mizrahi
Ulysse Mizrahi

Reputation: 681

Scala type inference with function types

Consider the following piece of code : (see below for the actual code that needs solving)

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))

(given a Seq of T => S and a value, we expect to get the funtions applied on this value).

Although applyAll compiles fine, calling it on u gives the following error :

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))
        ^

Which indicates that the compiler can't infer the type parameter S, which I'm guessing is because it is 'nested' inside a function type T => S.


Edit:

The actual code I'm trying to fix is similar (albeit complicated), and can't be fixed by removing the U parameter. Here goes :

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)

Upvotes: 2

Views: 258

Answers (2)

Kolmar
Kolmar

Reputation: 14224

You can make Repr a higher-kinded type Repr[_], and make the jobs argument have the type Repr[T => S]:

def applyNatural[T, S, Repr[A] <: TraversableLike[A, Repr[A]], That]
  (data: T, jobs: Repr[T => S])
  (implicit bf: CanBuildFrom[Repr[T => S], S, That]
): That = {
  jobs.map(f => f(data))
}

Upvotes: 3

Nabil A.
Nabil A.

Reputation: 3400

The U is simply useless. Just write

  def applyAll[T,S](l :  Seq[T => S], x: T) = l.map(f => f(x))
  val u = List((i: Int) => i + 1, (i: Int) => i + 2)
  println(applyAll(u,1))

Upvotes: 4

Related Questions