【发布时间】:2018-07-24 06:53:26
【问题描述】:
我遇到了许多用例,在这些用例中,我已经在使用类型参数边界的上下文中尝试编写 Functor、Applicative、Monad 等实例。
例如...
import cats._
trait Preference[A] extends Order[A]
trait SocialWelfareFunction[-CC <: Iterable[P], +P <: Preference[_]]
extends (CC => P)
object SocialWelfareFunction {
def functor: Functor[({ type F[P <: Preference[_]] = SocialWelfareFunction[Iterable[P], P] })#F] = {
???
}
...当我尝试编译它时,我会收到以下错误。
kinds of the type arguments ([P <: Playground.this.Preference[_]]Playground.this.SocialWelfareFunction[Iterable[P],P]) do not conform to the expected kinds of the type parameters (type F) in trait Monad.
[P <: Playground.this.Preference[_]]Playground.this.SocialWelfareFunction[Iterable[P],P]'s type parameters do not match type F's expected parameters:
type P's bounds <: Playground.this.Preference[_] are stricter than type _'s declared bounds >: Nothing <: Any
如何为我也使用类型参数的上下文编写 Functor、Applicative、Monad 等实例?甚至可能吗?有没有更合适的前进方式?
【问题讨论】:
-
如果
SocialWelfareFunction[C, ?]应该是第二个组件中的Functor,那么它必须有一个接受f: A => B并将SocialWelfareFunction[C, A]映射到SocialWelfareFunction[C, B]的map。你能想象一个map-实现可以将Preference[_]映射到List[Int]或JsonNode或(Unit, Preference[_])或Either[String, Double]吗?如果不是,那么它就不是函子。仔细挑选类型A和B不会有太大帮助,因为函子和 monad 上的许多有趣结构依赖于函子F能够将F[A]映射到例如F[Either[X, A]]. -
也许我真正想说的不是
P <: Preference[A],而是P定义了一个类型类Order[A]的实例。这可能吗? -
这里是example with typeclass(这里需要
Encoder[A]而不是Order[A],但有点相似)。实际上,应该有可能以类似的方式为具有参数界限的类型构造函数获取“函子”。我会草拟一份提案(可能需要几分钟)。 -
我有一个关于如何为具有类型边界并依赖于类型类的类型构造函数定义
Functor实例的一般演示,但我仍然不明白你想用 @987654353 在那里实现什么@。看来你想定义一个仿函数F[P] = (Iterable[P] => P),这是不可能的(因为P既是输入又是输出,这使得它与Endomorphisms[P]非常相似,它也不是仿函数,无论类型系统或语言)。 -
@davidpugh 发布了具有上限类型边界和类型类的“几乎函子”的通用解决方案。它与之前链接的答案基本相同。我想我会将其转换为“规范的”问答对,稍后我可以链接到该对,因为这个问题似乎反复出现。
标签: scala functional-programming functor type-parameter scala-cats