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

CoflatMap Instance for Applicative #2112

Merged
merged 2 commits into from
Dec 16, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions core/src/main/scala/cats/Applicative.scala
Original file line number Diff line number Diff line change
Expand Up @@ -207,6 +207,28 @@ object Applicative {
*/
implicit def catsApplicativeForArrow[F[_, _], A](implicit F: Arrow[F]): Applicative[F[A, ?]] =
new ArrowApplicative[F, A](F)


/**
* Creates a CoflatMap for an Applicative `F`.
* Cannot be implicit in 1.0 for Binary Compatibility Reasons
*
* Example:
* {{{
* scala> import cats._
* scala> import cats.implicits._
* scala> val fa = Some(3)
* fa: Option[Int] = Some(3)
* scala> Applicative.coflatMap[Option].coflatten(fa)
* res0: Option[Option[Int]] = Some(Some(3))
* }}}
*/
def coflatMap[F[_]](implicit F: Applicative[F]): CoflatMap[F] =
new CoflatMap[F] {
def coflatMap[A, B](fa: F[A])(f: F[A] => B): F[B] = F.pure(f(fa))
def map[A, B](fa: F[A])(f: A => B): F[B] = F.map(fa)(f)
}

}

private[cats] class ApplicativeMonoid[F[_], A](f: Applicative[F], monoid: Monoid[A]) extends ApplySemigroup(f, monoid) with Monoid[F[A]] {
Expand Down
13 changes: 13 additions & 0 deletions tests/src/test/scala/cats/tests/ApplicativeSuite.scala
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@ package cats
package tests

import cats.Applicative
import cats.data.{Validated, Const}
import cats.laws.discipline.arbitrary._
import cats.laws.discipline.CoflatMapTests


class ApplicativeSuite extends CatsSuite {
Expand Down Expand Up @@ -36,4 +39,14 @@ class ApplicativeSuite extends CatsSuite {
}
}

implicit val listwrapperApplicative = ListWrapper.applicative
implicit val listwrapperCoflatMap = Applicative.coflatMap[ListWrapper]
checkAll("Applicative[ListWrapper].coflatMap", CoflatMapTests[ListWrapper].coflatMap[String, String, String])

implicit val validatedCoflatMap = Applicative.coflatMap[Validated[String, ?]]
checkAll("Applicative[Validated].coflatMap", CoflatMapTests[Validated[String, ?]].coflatMap[String, String, String])

implicit val constCoflatMap = Applicative.coflatMap[Const[String, ?]]
checkAll("Applicative[Const].coflatMap", CoflatMapTests[Const[String, ?]].coflatMap[String, String, String])

}