为Seq [A]和Map [A​​,Int]键入类语法

时间:2016-07-20 20:55:00

标签: scala typeclass

我正在编写一个类型类来表示实验观察的集合。我丰富SeqMap的语法特征似乎很差。可以改进吗?

目标:

assert(5 == Seq("a", "a", "b", "b", "c").numObs)
assert(5 == Map("a" -> 2, "b" -> 2, "c" -> 1).numObs)

我的(大大简化)类型类:

trait Observations[A, T[_]] {
  def numObs(t: T[A]): Int
}

Seq和频率表的实例:

object Observations{

  implicit def seqIsObservations[A]: Observations[A, Seq] = new Observations[A, Seq] {
    def numObs(t: Seq[A]) = t.size
  }

  implicit def freqTableIsObservations[A]: Observations[A, ({ type λ[A] = Map[A, Int] })#λ] = 
      new Observations[A, ({ type λ[A] = Map[A, Int] })#λ] {
    def numObs(t: Map[A, Int]) = t.values.sum
  }
}

我提出的最佳语法:

trait ObservationsSyntax {

  implicit class ObservationsOps[A, T[_]](thiz: T[A]) {
    def numObs(implicit instance: Observations[A, T]): Int = 
      instance.numObs(thiz)
  }

  //Don’t like having to have this special case
  implicit class ObservationsMAPOps[A](thiz: Map[A, Int]) {
    def numObs(implicit instance: Observations[A, ({ type λ[A] = Map[A, Int] })#λ]): Int = 
      instance.numObs(thiz)
  }
}

有没有办法使用类型lambdas来消除语法特征中的第二个隐含?

0 个答案:

没有答案