2014-09-03 83 views
1

这是在一个情况下,有必要有一些非常相似的番石榴多集。我已经使用了Scala MultiMap,将它作为一个特征来混合。我尝试为MultiSet做些事情。斯卡拉,类型clases和执法

trait MultiSet[A] extends mutable.Map[A, Int] { 

    def setCount(e:A, count:Int):Unit = { 
    this.update(e, this.getCount(e) + count) 
    } 

    def getCount(e:A): Int = this.getOrElse(e, 0) 

} 

我用它为:

scala> val degree = new mutable.HashMap[String, Int] with MultiSet[String, Int] 

scala> degree.getCount("a") 
res0: Int = 0 

scala> degree.setCount("a", 1) 

scala> degree.setCount("a", 2) 

scala> degree.getCount("a") 
res1: Int = 3 

我想要做一个额外的步骤(可能是不必要的,但对于int应该是足够了),我这样写:

trait MultiSet[A, T] extends mutable.Map[A, T] { 

    def setCount(e:A, count:T)(implicit num: Numeric[T]):Unit = { 
    this.update(e, num.plus(this.getCount(e), count)) 
    } 

    def getCount(e:A)(implicit num: Numeric[T]): T = this.getOrElse(e, num.zero) 

} 

我问题是有一种方法可以在T上执行执行来告诉编译器该类型应该存在一个Numeric [T]吗?

回答

2

解决方法与同伴反对

trait MultiSet[A, T] extends mutable.Map[A, T] { 

    protected def numeric: Numeric[T] 

    def setCount(e:A, count:T):Unit = { 
     this.update(e, numeric.plus(this.getCount(e), count)) 
    } 

    def getCount(e:A): T = this.getOrElse(e, numeric.zero) 
    } 

    object MultiSet { 
    def empty[A, T: Numeric] = new mutable.HashMap[A, T] with MultiSet[A, T] { 
     val numeric: Numeric[T] = implicitly[Numeric[T]] 
    } 
    } 

    val degreeInt = MultiSet.empty[String, Int] // Ok 
    val degreeString = MultiSet.empty[String, String] // Compile Error 
+0

是执行其“创造”的好办法。我喜欢。谢谢! – Joselo 2014-09-03 21:36:39