首页 > 解决方案 > 对猫的逆变函子应用、应用、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 中是否存在用于逆变函子的这些类型类的版本?

标签: scalafunctorscala-cats

解决方案


ApplicativeHaskell 中的逆变等价物是Divisible,并且cats.ContravariantMonoidal 允许定义它的两个方法(divideis contramap2conqueris trivial。不过,我不能立即确定是否DivisibleMonoidal猫的意义。

对于Monad, Kmett 说

不存在类似单子的逆变。你需要 C -> C,而不是 C -> C^op。扭曲使您无法构建良好的结构。

还有逆变单子吗?.


推荐阅读