Dedicated Functional Outputs

I am looking for a function that takes a tuple of functions over a common domain and returns a function from that domain to a tuple of its corresponding outputs. I assume that such a utility is either built into Scala or hidden somewhere in Scalaz, but I could not find it.

For example, a special case of a pair of functions (and taking functions as separate arguments, rather than a pair) would look like this:

def pairFunc[I, O1, O2](f: I => O1, g: I => O2): I => (O1, O2) = (x: I) => (f(x), g(x))

Is there a way to achieve this for an arbitrary set of functions?

EDIT:

A method of type Function whose result looks like X -> ((A, B), C)and whose construction looks like f fZip g fZip his just as good as a function whose output X -> (A, B, C).

+4
source share
2 answers

, scalaz (7) &&&:

  import scalaz._
  import Scalaz._

  val intToString = (i:Int) => i.toString
  val intPlusTwo = (i:Int) => i + 2

  val combined = intToString &&& intPlusTwo

  println(combined(1)) // (1, 3)

, :

  val combinedMore = intToString &&& intPlusTwo &&& intToString

  println(combinedMore(1)) // ((1,3),1)
+4

, <%

// Add untupling capacity to a simple pair
implicit class EnrichTuple [A, B, C](f: (Function1[A, B], Function1[A, C])) {
  def untuple = (a: A) => (f._1(a), f._2(a))
}
// Add untupling capacity to a pair where the first member can implicitly be untupled
implicit class EnrichTuple2 [A, C, AB <% Function1[A, B] forSome { type B }](f: (AB, Function1[A, C])) {
  def untuple = (a: A) => (f._1(a), f._2(a))
}
// Add untupling capacity to a pair where the second member can implicitly be untupled
implicit class EnrichTuple3 [A, B, AC <% Function1[A, C] forSome { type C }](f: (Function1[A, B], AC)) {
  def untuple = (a: A) => (f._1(a), f._2(a))
}

val intToString = (i:Int) => i.toString
val intPlusTwo = (i:Int) => i + 2
val intTimesFour = (i: Int) => i * 4

val res1 = (intToString, intPlusTwo).untuple
val res2 = ((intToString, intPlusTwo), intTimesFour).untuple
val res3 = (intToString, (intPlusTwo, intTimesFour)).
res1(1)  // Returns (1, 3)
res2(1)  // Returns ((1, 3),4)
res3(1)  // Returns (1, (3, 4))
val res4 = ((intToString, intTimesFour), (intPlusTwo, intTimesFour )).untuple // Error 

, scalaz, , . , , .

+1

All Articles