Skip to content

Instantly share code, notes, and snippets.

@fancellu
Created May 26, 2020 11:26
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fancellu/363cd8b34a877224c925c6bb46fbed9e to your computer and use it in GitHub Desktop.
Save fancellu/363cd8b34a877224c925c6bb46fbed9e to your computer and use it in GitHub Desktop.
Example usage of Cats Bifunctor/Bifoldable/Bitraverse functions
import cats._
import cats.data._
import cats.syntax._
import cats.implicits._
object CatsBi extends App {
val fail = Left("failed")
val ok = Right(123)
// from Bifunctor
def mybimap(e: Either[String, Int]): Either[String, String] = {
e.bimap(_ + "!!", i => (i * 10).toString)
}
println(mybimap(fail))
println(mybimap(ok))
// from Bifunctor
def myleftmap(e: Either[String, Int]): Either[String, Int] = {
e.leftMap(_ + "!!!!!!!!")
}
println(myleftmap(fail))
println(myleftmap(ok))
// from Bifoldable
def myfoldleft(e: Either[String, Int]): String = {
e.bifoldLeft("either=")((acc, fail) => acc + fail, (acc, ok) => acc + ok)
}
println(myfoldleft(fail))
println(myfoldleft(ok))
// from Bifoldable, but this time using the Monoid of String to compose
def myfoldmap(e: Either[String, Int]): String = {
e.bifoldMap(identity, _.toString)
}
println(myfoldmap(fail))
println(myfoldmap(ok))
def myfold(e: Either[String, Int]): (String, Int) = {
e.bifold
}
// from Bifoldable, but this time using the Monoid of String and Int to compose a tuple
println(myfold(fail))
println(myfold(ok))
// from Bitraverse
def mytraverse(e: Either[String, Int]): List[Either[Throwable, String]] = {
e.bitraverse((f: String) => if (f.isEmpty) Nil else List(new Throwable(f)), (i: Int) => List(i.toString))
}
println(mytraverse(fail))
println(mytraverse(ok))
println(List(fail, Left(""), ok).flatMap(mytraverse))
}
Left(failed!!)
Right(1230)
Left(failed!!!!!!!!)
Right(123)
either=failed
either=123
failed
123
(failed,0)
(,123)
List(Left(java.lang.Throwable: failed))
List(Right(123))
List(Left(java.lang.Throwable: failed), Right(123))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment