[英]Converting functors (F[A] => G[A]) in Scala (cats or scalaz)
Is there a typeclass in Cats or Scalaz that converts between different container types? 在Cats或Scalaz中是否存在可在不同容器类型之间进行转换的类型类? 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. 似乎
FunctionK
/ ~>
/ NaturalTransformation
可能是我正在寻找的,但没有为它们定义任何实例,我不知道为什么。
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). 它们定义了仿函数之间的态射(在本例中,
List[A]
和Option[A]
类型构造函数)。 You can define one using the ~>
"operator" in Scalaz: 您可以使用Scalaz中的
~>
“operator”定义一个:
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[_]]
: ~>
是性状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
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.