Skip to content

Commit

Permalink
Added examples for Cokleisli (#1993)
Browse files Browse the repository at this point in the history
* Example for beginners to use Arrow composition

* Example for beginners to use Arrow composition

* Got rid of whitespace at EOL

* Added type signatures

* Got rid of the unused import that is borking the build

* Added examples for dimap,lmap,rmap for Cokleisli

* Exchanged the Cokleisli Id examples with NonEmptyList

* Revert "Exchanged the Cokleisli Id examples with NonEmptyList"

This reverts commit 50dd65e.

* Exchanged the Cokleisli examples from 'Id' to use 'NonEmptyList' instead

* Removed redundant renderings

* This is probably safer.

* doh.have not quite woke up yet.
  • Loading branch information
raymondtay authored and kailuowang committed Oct 29, 2017
1 parent 58a9fd6 commit c4ee747
Showing 1 changed file with 32 additions and 0 deletions.
32 changes: 32 additions & 0 deletions core/src/main/scala/cats/data/Cokleisli.scala
Original file line number Diff line number Diff line change
Expand Up @@ -11,15 +11,47 @@ import scala.annotation.tailrec
*/
final case class Cokleisli[F[_], A, B](run: F[A] => B) { self =>

/**
* Example:
* {{{
* scala> import cats._, data._
* scala> val f = Cokleisli((xs: NonEmptyList[Int]) => xs.reverse.head)
* scala> def before(x: Double) = x.toInt
* scala> def after(x: Int) = x.toString
* scala> f.dimap(before)(after).run(NonEmptyList.of(1.0,2.0))
* res0: String = 2
* }}}
*/
def dimap[C, D](f: C => A)(g: B => D)(implicit F: Functor[F]): Cokleisli[F, C, D] =
Cokleisli(fc => g(run(F.map(fc)(f))))

/**
* Example:
* {{{
* scala> import cats._, data._, implicits._
* scala> val f = Cokleisli((xs: NonEmptyList[Int]) => xs.reverse.head)
* scala> def before(x: Double) = x.toInt
* scala> def after(x: Int) = x.toString
* scala> f.lmap(before).rmap(after).run(NonEmptyList.of(1.0,2.0))
* res0: String = 2
* }}}
*/
def lmap[C](f: C => A)(implicit F: Functor[F]): Cokleisli[F, C, B] =
Cokleisli(fc => run(F.map(fc)(f)))

def map[C](f: B => C): Cokleisli[F, A, C] =
Cokleisli(f compose run)

/**
* Example:
* {{{
* scala> import cats._, data._
* scala> val sum = Cokleisli((xs: NonEmptyList[Int]) => xs.reduceLeft(_ + _))
*
* scala> sum.contramapValue((xs: NonEmptyList[String]) => xs.map(_.toInt)).run(NonEmptyList.of("1","2","3"))
* res4: Int = 6
* }}}
*/
def contramapValue[C](f: F[C] => F[A]): Cokleisli[F, C, B] =
Cokleisli(run compose f)

Expand Down

0 comments on commit c4ee747

Please sign in to comment.