Skip to content

Commit

Permalink
Enrich return type for Representable.apply and add doctests (#2426)
Browse files Browse the repository at this point in the history
The `Representable.apply` method was discarding information about its
return type in a way that made it not very helpful for some use-cases. I
believe that the change that I made to it makes it strictly more useful
in a compatible way, but let me know if that doesn't seem to be the
case.

While creating this I noticed that our Representable instance for Tuple2
uses true for the first index and false for the second index. I'm not
familiar with any precedents in this area, but I would have expected
false = 0 index and true = 1 index.  I assume that this is intended?

I also added several scaladoc examples, because why not?!
  • Loading branch information
ceedubs authored and Luka Jacobowitz committed Sep 5, 2018
1 parent 6bfe64e commit b3c704f
Showing 1 changed file with 41 additions and 1 deletion.
42 changes: 41 additions & 1 deletion core/src/main/scala/cats/Representable.scala
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,41 @@ trait Representable[F[_]] extends Serializable {

/**
* Create a function that "indexes" into the `F` structure using `Representation`
*
* Example:
* {{{
* scala> import cats.implicits._
*
* scala> type Pair[A] = (A, A)
*
* scala> val indexed: Boolean => String = Representable[Pair].index(("foo", "bar"))
*
* scala> indexed(true)
* res0: String = foo
*
* scala> indexed(false)
* res1: String = bar
* }}}
*/
def index[A](f: F[A]): Representation => A

/**
* Reconstructs the `F` structure using the index function
*
* Example:
* {{{
* scala> import cats.implicits._
*
* scala> type Pair[A] = (A, A)
*
* scala> val f: Boolean => String = {
* | case true => "foo"
* | case false => "bar"
* | }
*
* scala> f.tabulate[Pair]
* res0: Pair[String] = (foo,bar)
* }}}
*/
def tabulate[A](f: Representation => A): F[A]
}
Expand Down Expand Up @@ -69,8 +99,18 @@ object Representable {

/**
* Summon the `Representable` instance for `F`
*
* Example:
* {{{
* scala> import cats.implicits._
*
* scala> type Pair[A] = (A, A)
*
* scala> Representable[Pair].index(("foo", "bar"))(false)
* res0: String = bar
* }}}
*/
def apply[F[_]](implicit ev: Representable[F]): Representable[F] = ev
def apply[F[_]](implicit ev: Representable[F]): Representable.Aux[F, ev.Representation] = ev

/**
* Derives a `Monad` instance for any `Representable` functor
Expand Down

0 comments on commit b3c704f

Please sign in to comment.