2014-09-03 84 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