【问题标题】:Scala unable to change values in mutable Map[Char, Map[Int, Double]] with default valuesScala 无法使用默认值更改可变 Map[Char, Map[Int, Double]] 中的值
【发布时间】:2013-10-21 14:31:06
【问题描述】:

由于完整代码中前面的 import 语句,此代码中的所有映射都是可变映射。 nGramGetter.getNGrams(...) 方法调用返回一个 Map[String, Int]。

  def train(files: Array[java.io.File]): Map[Char, Map[Int, Double]] = {
    val scores = Map[Char, Map[Int, Double]]().withDefault( x => Map[Int, Double]().withDefaultValue(0.0)) 

    for{
      i <- 1 to 4
      nGram <- nGramGetter.getNGrams(files, i).filter( x => (x._1.size == 1 || x._2 > 4) && !hasUnwantedChar(x._1) )
      char <- nGram._1
    } scores(char)(i) += nGram._2
    println(scores.size)
    val nonUnigramTotals = scores.mapValues( x => x.values.reduce(_+_)-x(1) )    

    val unigramTotals = scores.mapValues( x => x(1) )

    scores.map( x => x._1 -> x._2.map( y => y._1 -> (if(y._1 > 1) y._2/unigramTotals(x._1) else (y._2-nonUnigramTotals(x._1))/unigramTotals(x._1)) ) )
  }

我已将scores(char)(i) += nGram._2 行替换为一些打印语句(打印每个键中的键、值和单个字符)以检查输出,并且方法调用未返回空列表。但是,打印scores 大小的行正在打印零。我几乎可以肯定我之前已经使用过这种方法来填充频率图,但是这一次,地图总是空的。我已将 withDefault 更改为 withDefaultValue 并将当前函数文字的结果作为参数传递。我已经用Map[Int, Double](1-&gt;0.0,2-&gt;0.0,3-&gt;0.0,4-&gt;0.0) 尝试了withDefaultwithDefaultValue。我有点 Scala 菜鸟,所以也许我只是不了解导致问题的语言。知道有什么问题吗?

【问题讨论】:

    标签: scala maps default-value scala-collections mutable


    【解决方案1】:

    withDefaultwithDefaultValue 方法不会更改地图。相反,它们只是返回一个默认值。让我们从语句中删除语法糖,看看哪里出了问题:

    scores(char)(i) += nGram._2
    scores(char)(i) = scores(char)(i) + nGram._2
    scores.apply(char)(i) = scores.apply(char)(i) + nGram._2
    scores.apply(char).update(i, scores.apply(char).apply(i) + nGram._2)
    

    现在,由于scores.apply(char) 不存在,因此返回默认值Map[Int, Double]().withDefaultValue(0.0),并且 映射被修改。不幸的是,它永远不会被分配给scores,因为它没有调用update 方法。试试下面的代码——它未经测试,但应该不难让它工作:

    scores(char) = scores(char) // initializes the map for that key, if it doesn't exist
    scores(char)(i) += nGram._2
    

    【讨论】:

    • 现在完美运行。非常感谢!
    猜你喜欢
    • 2011-01-20
    • 1970-01-01
    • 2020-09-12
    • 2020-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-01
    • 1970-01-01
    相关资源
    最近更新 更多