Reputation: 1339
Is there a typeclass in Cats or Scalaz that converts between different container types? For example
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.
Upvotes: 4
Views: 552
Reputation: 149518
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
}
Upvotes: 5