【问题标题】:Can I write a scala function that returns an n-tuple where n is defined by an argument?我可以编写一个返回 n 元组的 scala 函数,其中 n 由参数定义吗?
【发布时间】:2015-02-02 20:21:21
【问题描述】:

我正在尝试编写一个从推文生成 n-gram 的 scala 函数。

该函数将接受两个参数,第一个是字符串列表(我们要检查的推文),另一个是整数 n。如果我们将 n 设置为 2(默认值),则函数的结果将是 2-tuples 的 HashMultiset,同样如果我们将其设置为 3,则结果将是 3-tuples 的 HashMultiset。

有没有办法定义这样的函数?我想明确我的输入,所以我不想只将函数定义为返回 Any 的 MultiSet。

这是我目前拥有的存根函数,它只适用于 n==2:

def extract_ngrams(tweets:List[String], n:Int=2):HashMultiset[(String,String)] = {
val result = HashMultiset.create[(String,String)]()
result.add(("a", "a"))
result
}

【问题讨论】:

    标签: scala


    【解决方案1】:

    Scala 中的元组最多只能达到 22 个。因此,即使有可能它也只允许 n 个 2..22 的值。

    我会改为简单地返回 HashMultiset[Array[String]] 并且您可以使用 n 来定义您的结果: val result = HashMultiset[Array[String]].create()

    然后,您可以在需要时根据用例map it to tuples

    更新

    如果我了解您的需求,我会做类似的事情

    def extract_ngrams(tweets:List[String], n:Int=2):Map[List[String],Int] = {
       tweets.sliding(n).toList.groupBy(_.toList).mapValues(_.length)
    }
    

    【讨论】:

      【解决方案2】:

      这在原生 Scala 库中是不可能的。如果此功能对您很重要,您可以使用 shapeless 之类的东西。

      您所描述的元组的常见超类型是 Product with Serializable,因此您可以根据需要返回 HashMultiset[Product with Serializable],但您最好只返回 HashMultiset[Seq[String]]HashMultiset[Map[Int, String]] 或 @ 987654326@.

      【讨论】:

        【解决方案3】:

        我建议元组可能是错误的数据结构。一个案例类可以巧妙地解决这个问题:

        case class Data(v: String*)
        
        def makeData(v: String*) = {
          Data(v: _*)
        }
        
        val s = Set[Data]()
        
        s += makeData("a", "b")
        s += makeData("c", "d", "e")
        
        for(i <- s) i match {
          case Data(v @ _*) => println(v)
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-11-14
          • 1970-01-01
          • 2013-11-08
          • 2016-11-27
          • 2014-10-08
          • 2019-02-28
          相关资源
          最近更新 更多