1

IntHistogram 对单词进行计数并按计数降序显示:

object IntHistogram {

  def main(args: Array[String]) {
    val wordsToCount = "foo foo bar foo bar wtf foo bar".split(" ")
    val histogram = new IntHistogram
    for (word <- wordsToCount) histogram(word) += 1
    println(histogram)
    /* 
       (foo,4)
       (bar,3)
       (wtf,1)
    */
  }

}

class IntHistogram extends collection.mutable.HashMap[String,Int] {
  override def default(key:String) = 0
  def descendingPairs = toList.sortBy(_._2).reverse
  override def toString() = descendingPairs.mkString("\n")
}

我需要一个 DoubleHistogram,我使用了复制粘贴,因为我不知道如何定义一个通用的“Histogram[NumberSuperClassOfIntAndDouble]”特征:

class DoubleHistogram extends collection.mutable.HashMap[String,Double] {
  override def default(key:String) = 0
  def descendingPairs = toList.sortBy(_._2).reverse
  override def toString() = descendingPairs.mkString("\n")
}

一个聪明/知识渊博的人可以告诉我如何定义这样的超级特征,这样我就可以避免丑陋的复制粘贴样板吗?

提前致谢,

PT

PS我真的希望直方图成为一个特征,所以我可以将直方图行为混合到任何数值地图中。实际上,除了降序 toString 方法之外,我还需要很多行为;我为这个问题简化了它。这里 Num 是 Int 和 Double 的虚构数字超类:

trait Histogram[Num] extends collection.Map[String,Num] {
  override def default(key:String) = 0
  def descendingPairs = toList.sortBy(_._2).reverse
  override def toString() = descendingPairs.mkString("\n")
}

我尝试使用 Numeric、Number、import Ordering.Implicits._、各种东西......无济于事。

4

1 回答 1

2

这似乎与Numeric. Histogram并不是因为上下文绑定在 上,你不能做出特征N,而是IntHistogramandDoubleHistogram可以是特征。

object IntHistogram {

  def main(args: Array[String]) {
    val wordsToCount = "foo foo bar foo bar wtf foo bar".split(" ")
    val histogram = new IntHistogram {}
    for (word <- wordsToCount) histogram(word) += 1
    println(histogram)
    /* 
       (foo,4)
       (bar,3)
       (wtf,1)
    */
  }

}

abstract class Histogram[N:Numeric] extends collection.mutable.HashMap[String,N] {
  override def default(key:String) = implicitly[Numeric[N]].zero
  def descendingPairs = toList.sortBy(_._2).reverse
  override def toString = descendingPairs.mkString("\n")
}

trait IntHistogram extends Histogram[Int]
trait DoubleHistogram extends Histogram[Double]

如果你真的,真的需要直方图成为一个特征,你可以这样做:

trait Histogram[N] extends collection.mutable.HashMap[String,N] {
  implicit val n:Numeric[N]
  override def default(key:String) = n.zero
  def descendingPairs = toList.sortBy(_._2).reverse
  override def toString = descendingPairs.mkString("\n")
}

但是你必须在 main 中像这样实例化它:

val histogram = new Histogram[Int] { val n = implicitly[Numeric[Int]] }
于 2012-10-04T17:16:22.163 回答