2
votes

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)
2
I see two problems with the edit code: First, Repr is cyclic. To resolve Repr you must look up Repr. Second, there is no build from. - Nabil A.
What do you actually want to do? - Nabil A.
I'm looking to create a function which can apply a collection of functions to a value, and return a collection of values of the same type. - Ulysse Mizrahi
So input is Collection of functions and a value of type T and it should return collection of T? - Nabil A.

2 Answers

4
votes

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

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