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

Add Traverse and Comonad instances for Tuple2. #1220

Merged
merged 1 commit into from
Jul 20, 2016
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
18 changes: 18 additions & 0 deletions core/src/main/scala/cats/instances/tuple.scala
Original file line number Diff line number Diff line change
Expand Up @@ -21,4 +21,22 @@ sealed trait Tuple2Instances {
s"(${aShow.show(f._1)},${bShow.show(f._2)})"
}
}

implicit def catsStdInstancesForTuple2[X]: Traverse[(X, ?)] with Comonad[(X, ?)] =
new Traverse[(X, ?)] with Comonad[(X, ?)] {
def traverse[G[_], A, B](fa: (X, A))(f: A => G[B])(implicit G: Applicative[G]): G[(X, B)] =
G.map(f(fa._2))((fa._1, _))

def foldLeft[A, B](fa: (X, A), b: B)(f: (B, A) => B): B = f(b, fa._2)

def foldRight[A, B](fa: (X, A), lb: Eval[B])(f: (A, Eval[B]) => Eval[B]): Eval[B] = f(fa._2, lb)

override def map[A, B](fa: (X, A))(f: A => B): (X, B) = (fa._1, f(fa._2))

def coflatMap[A, B](fa: (X, A))(f: ((X, A)) => B): (X, B) = (fa._1, f(fa))

def extract[A](fa: (X, A)): A = fa._2

override def coflatten[A](fa: (X, A)): (X, (X, A)) = (fa._1, fa)
}
}
8 changes: 7 additions & 1 deletion tests/src/test/scala/cats/tests/TupleTests.scala
Original file line number Diff line number Diff line change
@@ -1,12 +1,18 @@
package cats
package tests

import cats.laws.discipline.{BitraverseTests, SerializableTests}
import cats.laws.discipline.{BitraverseTests, ComonadTests, SerializableTests, TraverseTests}

class TupleTests extends CatsSuite {
checkAll("Tuple2", BitraverseTests[Tuple2].bitraverse[Option, Int, Int, Int, String, String, String])
checkAll("Bitraverse[Tuple2]", SerializableTests.serializable(Bitraverse[Tuple2]))

checkAll("Tuple2[String, Int] with Option", TraverseTests[(String, ?)].traverse[Int, Int, Int, Int, Option, Option])
checkAll("Traverse[(String, ?)]", SerializableTests.serializable(Traverse[(String, ?)]))

checkAll("Tuple2[String, Int]", ComonadTests[(String, ?)].comonad[Int, Int, Int])
checkAll("Comonad[(String, ?)]", SerializableTests.serializable(Comonad[(String, ?)]))

test("eqv") {
val eq = Eq[(Int, Long)]
forAll { t: (Int, Long) => eq.eqv(t, t) should === (true) }
Expand Down