scala - 对猫的逆变函子应用、应用、Monad 等?
问题描述
我有以下特点...
import cats._
import cats.implicits._
trait Preference[-A] {
self =>
def compare(a1: A, a2: A): Int
final def ordering[A1 <: A]: Ordering[A1] = {
new Ordering[A1] {
def compare(a1: A1, a2: A1): Int = {
self.compare(a1, a2)
}
}
}
}
object Preference {
implicit val contravariant: Contravariant[Preference] = {
new Contravariant[Preference] {
def contramap[A, B](fa: Preference[A])(f: B => A): Preference[B] = {
new Preference[B] {
def compare(b1: B, b2: B): Int = {
fa.compare(f(b1), f(b2))
}
}
}
}
}
}
我想定义Apply
, Applicative
, 甚至可能是Monad
这个 trait 的实例,但所有这些类型类都是Functor
. Cats 中是否存在用于逆变函子的这些类型类的版本?
解决方案
Applicative
Haskell 中的逆变等价物是Divisible
,并且cats.ContravariantMonoidal
允许定义它的两个方法(divide
is contramap2
,conquer
is trivial
)。不过,我不能立即确定是否Divisible
有Monoidal
猫的意义。
对于Monad
, Kmett 说
还有逆变单子吗?.