Transform an M[A => B] to an A => M[B]

Viewed 182

Does there exist a utility in Scala or Scalaz to transform a container/collection of functions to a function that maps from the same input to a collection output values? The signature would look something like

def transform[M[_], A, B](m: M[A => B]): A => M[B] = ???

Here's an example implementation for the 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 would work for any function container, including a tuple of functions, an Option[Function1[A, B]], or even a TupleN[Option[Function1[A, B]], ...].

EDIT:

I've just realized that (at least for the special case of a List) the map function works:

    def transform[A, B](fs: List[A => B]): A => List[B] = x => fs map (_(x))

This can generalize to anything that has a map function with the appropriate semantics. What's the appropriate type class for this?

2 Answers
Related