This question is based on the scala cats library, but I guess could apply to scalaz
or general functional programming.
I'm trying the cats exercises and I thought of the following functionality with Applicative
: Is there a function with the following signature and if so, what's it's name?
def foo[A[_]: Applicative, B, C, D](x: B, y: C)(f: (A[B], A[C]) => A[D]): A[D]
That is, if I have a function lying around that takes two Applicative
instances and produces a third as result (f
), I want to apply it to 2 values x
and y
without having to wrap it in an Applicative
myself with pure
. I can easily implement it myself like:
def pureMap[A[_]: Applicative, B, C, D](x: B, y: C)(f: (A[B], A[C]) => A[D]): A[D] = {
val ap = Applicative[A]
f(ap.pure(x), ap.pure(y))
}
but it looked like something that might exist already and I couldn't find anything. (pureMap
sounded like a reasonable name).
An example would be, if I already had a function in a validation library like:
def div(ox: Option[Int], oy: Option[Int]): Option[Int] =
for {
x <- ox
y <- oy
if y != 0
} yield x / y
, then I would want to use it like:
val z:Option[Int] = pureMap(2,0)(div)