Converting functors (F[A] => G[A]) in Scala (cats or scalaz)

551 views Asked by At

Is there a typeclass in Cats or Scalaz that converts between different container types? For example

  • Option ~> Try
  • Try ~> Future
  • Try ~> Either
  • Option ~> List

It seems like FunctionK/~>/NaturalTransformation may be what I'm looking for, but there aren't any instances defined for them and I don't know why.

1

There are 1 answers

0
Yuval Itzchakov On BEST ANSWER

Natural transformations are what you're looking for. They define morphisms between functors (In this case, the List[A] and the Option[A] type constructors). You can define one using the ~> "operator" in Scalaz:

def main(args: Array[String]): Unit = {
  val optionToList = new (Option ~> List) {
    override def apply[A](fa: Option[A]): List[A] = fa.toList
  }

  println(optionToList(Some(3)))
  println(optionToList(None))
}

Yields:

List(3)
Nil

The ~> is syntatic sugar for the trait NaturalTransformation[-F[_], +G[_]]:

/** A universally quantified function, usually written as `F ~> G`,
  * for symmetry with `A => B`.
  */
trait NaturalTransformation[-F[_], +G[_]] {
  self =>
  def apply[A](fa: F[A]): G[A]

  // Abbreviated for the answer
}