Is there a utility in Scala or Scalaz to convert a container / collection of functions into a function that maps from the same input to the output values of the collection? The signature will look something like this:
def transform[M[_], A, B](m: M[A => B]): A => M[B] = ???
Here's an example implementation for a List container:
def transform[A, B](fs: List[A => B]): A => List[B] = x =>
fs.foldRight[List[B]](Nil) {
(f, acc) => f(x) :: acc
}
Ideally, this will work for any container of functions, including a tuple of functions, Option[Function1[A, B]]or even TupleN[Option[Function1[A, B]], ...].
EDIT:
I just realized that (at least for the special case of the list) the map function works:
def transform[A, B](fs: List[A => B]): A => List[B] = x => fs map (_(x))
This can be generalized to everything that has a mapping function with appropriate semantics. What class is the appropriate class for this?
source
share