具有多种类型的类型的函子实现
Functor implementation for types with more than one type
假设我有:
trait Get[F[_], A, B]{
def get(a:A): F[B]
}
我希望能够映射结果类型 B,即我希望能够做到:
val getFoo: Get[IO, String, Foo] = ???
val foo2Bar: Foo => Bar = ???
val getBar: Get[IO, String, Bar] = getFoo.map(foo2Bar)
我知道我应该为 Get
实现一个 Functor
实例,但我正在努力,因为我不知道要使用什么类型的签名。
我尝试了以下方法:
implicit val functor:Functor[Get] = ???
implicit val functor: Functor[Lambda[(F[_], K, A) => Get[F, K, A]]] = ???
但它们似乎不是正确的类型,因为我似乎无法使用顶部所示的函子语法扩展。在这里表达类型的正确方法是什么?如果我使用 kind-projector
插件,等效类型是什么?
尝试
import cats.syntax.functor._
implicit def functor[F[_]: Functor, A]: Functor[Get[F, A, ?]] = new Functor[Get[F, A, ?]] {
override def map[B, B1](fa: Get[F, A, B])(f: B => B1): Get[F, A, B1] = a => fa.get(a).map(f)
}
假设我有:
trait Get[F[_], A, B]{
def get(a:A): F[B]
}
我希望能够映射结果类型 B,即我希望能够做到:
val getFoo: Get[IO, String, Foo] = ???
val foo2Bar: Foo => Bar = ???
val getBar: Get[IO, String, Bar] = getFoo.map(foo2Bar)
我知道我应该为 Get
实现一个 Functor
实例,但我正在努力,因为我不知道要使用什么类型的签名。
我尝试了以下方法:
implicit val functor:Functor[Get] = ???
implicit val functor: Functor[Lambda[(F[_], K, A) => Get[F, K, A]]] = ???
但它们似乎不是正确的类型,因为我似乎无法使用顶部所示的函子语法扩展。在这里表达类型的正确方法是什么?如果我使用 kind-projector
插件,等效类型是什么?
尝试
import cats.syntax.functor._
implicit def functor[F[_]: Functor, A]: Functor[Get[F, A, ?]] = new Functor[Get[F, A, ?]] {
override def map[B, B1](fa: Get[F, A, B])(f: B => B1): Get[F, A, B1] = a => fa.get(a).map(f)
}