Scala reduceByKey函数 – 使用任何具有方法的类型
发布时间:2020-12-16 19:20:21 所属栏目:安全 来源:网络整理
导读:我正在编写一个名为reduceByKey的简单函数,它接受(键,数字)对的集合并按键返回减少的集合. def reduceByKey[K](collection: Traversable[Tuple2[K,Int]]) = { collection .groupBy(_._1) .map { case (group: K,traversable) = traversable.reduce{(a,b) = (
我正在编写一个名为reduceByKey的简单函数,它接受(键,数字)对的集合并按键返回减少的集合.
def reduceByKey[K](collection: Traversable[Tuple2[K,Int]]) = { collection .groupBy(_._1) .map { case (group: K,traversable) => traversable.reduce{(a,b) => (a._1,a._2 + b._2)} } } 目前适用于: scala> val col = List((("some","key"),100),(("some","other",50)) col: List[(Product with Serializable,Int)] = List(((some,key),((some,other,50)) scala> reduceByKey(col) res42: scala.collection.immutable.Map[Product with Serializable,Int] = Map((some,key) -> 200,(some,key) -> 50) 但是,一旦我想将非Int类型用于数字,它就会失败,因为它需要一个Int. scala> val col = List((("some",100.toDouble),50.toDouble)) col: List[(Product with Serializable,Double)] = List(((some,100.0),50.0)) scala> reduceByKey(col) <console>:13: error: type mismatch; found : List[(Product with Serializable,Double)] required: Traversable[(?,Int)] reduceByKey(col) ^ 当然,我可以针对不同的类型制作不同的方法,但这很愚蠢.基本上我希望我的方法可以使用任何已定义方法的类型.那将是Double,Float,Long,Int和Short. >起初,我以为我可以使用结构类型而不是Int.但这意味着结构类型需要引用自身以便有用. 我对如何解决这个问题的任何建议持开放态度. 解决方法
如果您只对数值感兴趣,可以使用标准的数值类型类并执行以下操作:
def reduceByKey[K,V](collection: Traversable[Tuple2[K,V]])(implicit num: Numeric[V]) = { import num._ collection .groupBy(_._1) .map { case (group: K,a._2 + b._2)} } } num implicit参数用作V是数字类型的证据,并提供此类型的操作. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |