将 scalaz 的 === 用于 adt

use scalaz's === for adt's

我刚开始从 eugene's blog post 学习 scalaz。我正在尝试在我的代码中使用 === 但它 returns 是一个编译错误 value === is not a member of object Red

这是我的代码

import scalaz._

sealed trait TrafficLight
case object Red extends TrafficLight
case object Yellow extends TrafficLight
case object Green extends TrafficLight

object Equality {

import Scalaz._

def eqInstance[A](f: (A,A) => Boolean): Equal[A] = new Equal[A]{
    def equal(a1: A, a2: A): Boolean = f(a1,a2)    
}

def trafficLightEqualFunction(a1: TrafficLight, a2: TrafficLight): Boolean = (a1, a2) match {
    case (Red, Red) => true
    case (Yellow, Yellow) => true
    case (Green, Green) => true
    case _ => false
}

implicit val trafficLightEqual: Equal[TrafficLight] = eqInstance(trafficLightEqualFunction)

def main(args: Array[String]){
    println(Red === Red)
}

}

这正是他的博客所抱怨的。 Red 的类型是 Red.type 并且没有此类型的 scalaz.Equal 实例,因为 Equal 是不变的,所以尽管:

Red <: TrafficLight

不跟

Equal[Red] <: Equal[TrafficLight].

您可以通过让 Scala 将红色视为交通灯来修改它:

println((Red:TrafficLight) === (Red:TrafficLight))