且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Scala 中带有两个参数的类型构造函数的函子实例

更新时间:2023-11-12 17:22:40

您希望部分应用类型级构造函数.不幸的是,我们不能直接做到这一点.但是,我们仍然可以使用一个名为 Structural Types 的小功能间接地做到这一点.为了将 Foo 从双参数类型构造函数转变为单参数类型构造函数,我们将在匿名结构类型中定义类型同义词.

You're looking to partially apply a type-level constructor. Unfortunately, we can't directly do that. However, we can still do so indirectly using a little feature called Structural Types. In order to turn Foo from a two-argument type constructor into a one-argument type constructor, we'll define a type synonym inside of an anonymous, structural type.

implicit def fooInstances[X]: Functor[({ type T[A] = Foo[X, A] })#T] =
  new Functor[({ type T[A] = Foo[X, A] })#T] {
    // ...
  }

类型上下文中的大括号 {} 定义了一个匿名类型,我们正在利用该类型本质上在类型级别创建一个 lambda 函数.我们定义一个匿名类型,其中包含一个别名,然后立即评估该别名.

The braces {} in a type context define an anonymous type that we're exploiting to essentially create a lambda function at the type level. We define an anonymous type with an alias inside of it, then immediately evaluate that alias.