Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Optimize FreeApplicative.product #1921

Merged
merged 1 commit into from Sep 21, 2017
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
19 changes: 16 additions & 3 deletions free/src/main/scala/cats/free/FreeApplicative.scala
Expand Up @@ -32,6 +32,16 @@ sealed abstract class FreeApplicative[F[_], A] extends Product with Serializable
}
}

final def map2[B, C](fb: FA[F, B])(f: (A, B) => C): FA[F, C] =
this match {
case Pure(a) => fb.map(f(a, _))
case _ =>
fb match {
case Pure(b) => Ap(Pure(f((_: A), b)), this)
case _ => Ap(Ap(Pure((a: A) => (b: B) => f(a, b)), this), fb)
}
}

/** Interprets/Runs the sequence of operations using the semantics of `Applicative` G[_].
* Tail recursive.
*/
Expand Down Expand Up @@ -193,16 +203,19 @@ object FreeApplicative {
final def lift[F[_], A](fa: F[A]): FA[F, A] =
Lift(fa)

implicit final def freeApplicative[S[_]]: Applicative[FA[S, ?]] = {
implicit final def freeApplicative[S[_]]: Applicative[FA[S, ?]] =
new Applicative[FA[S, ?]] {
override def product[A, B](fa: FA[S, A], fb: FA[S, B]): FA[S, (A, B)] = ap(fa.map((a: A) => (b: B) => (a, b)))(fb)
override def product[A, B](fa: FA[S, A], fb: FA[S, B]): FA[S, (A, B)] =
map2(fa, fb)((_, _))

override def map[A, B](fa: FA[S, A])(f: A => B): FA[S, B] = fa.map(f)

override def ap[A, B](f: FA[S, A => B])(fa: FA[S, A]): FA[S, B] = fa.ap(f)

def pure[A](a: A): FA[S, A] = Pure(a)

override def map2[A, B, Z](fa: FA[S, A], fb: FA[S, B])(f: (A, B) => Z): FA[S, Z] =
fa.map2(fb)(f)
}
}

}