Skip to content

Commit

Permalink
Add Applicative.unit (#1586)
Browse files Browse the repository at this point in the history
* Add Applicative#unit

* Fix comment
  • Loading branch information
alexandru authored and kailuowang committed Apr 4, 2017
1 parent e77bb99 commit 43d205f
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 0 deletions.
8 changes: 8 additions & 0 deletions core/src/main/scala/cats/Applicative.scala
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,14 @@ import simulacrum.typeclass
*/
def pure[A](x: A): F[A]

/**
* Returns an `F[Unit]` value, equivalent with `pure(())`.
*
* A useful shorthand, also allowing implementations to optimize the
* returned reference (e.g. it can be a `val`).
*/
def unit: F[Unit] = pure(())

override def map[A, B](fa: F[A])(f: A => B): F[B] =
ap(pure(f))(fa)

Expand Down
3 changes: 3 additions & 0 deletions laws/src/main/scala/cats/laws/ApplicativeLaws.scala
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,9 @@ trait ApplicativeLaws[F[_]] extends ApplyLaws[F] {
def apProductConsistent[A, B](fa: F[A], f: F[A => B]): IsEq[F[B]] =
F.ap(f)(fa) <-> F.map(F.product(f, fa)) { case (f, a) => f(a) }

def applicativeUnit[A](a: A): IsEq[F[A]] =
F.unit.map(_ => a) <-> F.pure(a)

// The following are the lax monoidal functor identity laws - the associativity law is covered by
// Cartesian's associativity law.

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ trait ApplicativeTests[F[_]] extends ApplyTests[F] {
"applicative homomorphism" -> forAll(laws.applicativeHomomorphism[A, B] _),
"applicative interchange" -> forAll(laws.applicativeInterchange[A, B] _),
"applicative map" -> forAll(laws.applicativeMap[A, B] _),
"applicative unit" -> forAll(laws.applicativeUnit[A] _),
"ap consistent with product + map" -> forAll(laws.apProductConsistent[A, B] _),
"monoidal left identity" -> forAll((fa: F[A]) => iso.leftIdentity(laws.monoidalLeftIdentity(fa))),
"monoidal right identity" -> forAll((fa: F[A]) => iso.rightIdentity(laws.monoidalRightIdentity(fa))))
Expand Down

0 comments on commit 43d205f

Please sign in to comment.