元组中的 Scala 条件折叠(int,int)
Scala conditional fold in Tuple(int,int)
我有一个元组列表 (int,int) 例如
(100,3), (130,3), (160,1), (180,2), (200,2)
我想要 foldRight 或比较邻居的有效方法。对于 ((A1,A2),(B1,B2)),我们仅在 A2 小于或等于 B2 时才进行合并。否则,我们不会在该实例中折叠列表。如果我们合并,我们保留 (A1,A2) 并添加一个计数字段。
示例输出为
(100,3,2) 和 (160,1,3)
这里 2 和 3 是折叠到这个观察值的观察值的权重。
(100,3), (130,3)
将导致 (100,3,2)
同时
(160,1), (180,2), (200,2)
将导致 (160,1,3)
知道如何用 Scala 函数式风格编写它吗?
scala>def conditionalFold(in: List[(Int, Int)]): List[(Int, Int, Int)] =
| in.foldLeft(Nil: List[(Int, Int, Int)]) { (acc, i) =>
| acc match {
| case Nil =>
| (i._1, i._2, 1) :: Nil
| case head :: tail =>
| if (i._2 >= head._2)
| (head._1, head._2, head._3 + 1) :: tail
| else
| (i._1, i._2, 1) :: head :: tail
| }
| }.reverse
conditionalFold: (in: List[(Int, Int)])List[(Int, Int, Int)]
scala> println(conditionalFold(List((100, 3), (130, 3), (160, 1), (180, 2), (200, 2))))
List((100,3,2), (160,1,3))
scala> println(conditionalFold(List((100,3), (130,3))))
List((100,3,2))
scala> println(conditionalFold(List((160,1), (180,2), (200,2))))
List((160,1,3))
我有一个元组列表 (int,int) 例如
(100,3), (130,3), (160,1), (180,2), (200,2)
我想要 foldRight 或比较邻居的有效方法。对于 ((A1,A2),(B1,B2)),我们仅在 A2 小于或等于 B2 时才进行合并。否则,我们不会在该实例中折叠列表。如果我们合并,我们保留 (A1,A2) 并添加一个计数字段。 示例输出为
(100,3,2) 和 (160,1,3)
这里 2 和 3 是折叠到这个观察值的观察值的权重。
(100,3), (130,3)
将导致 (100,3,2)
同时
(160,1), (180,2), (200,2)
将导致 (160,1,3)
知道如何用 Scala 函数式风格编写它吗?
scala>def conditionalFold(in: List[(Int, Int)]): List[(Int, Int, Int)] =
| in.foldLeft(Nil: List[(Int, Int, Int)]) { (acc, i) =>
| acc match {
| case Nil =>
| (i._1, i._2, 1) :: Nil
| case head :: tail =>
| if (i._2 >= head._2)
| (head._1, head._2, head._3 + 1) :: tail
| else
| (i._1, i._2, 1) :: head :: tail
| }
| }.reverse
conditionalFold: (in: List[(Int, Int)])List[(Int, Int, Int)]
scala> println(conditionalFold(List((100, 3), (130, 3), (160, 1), (180, 2), (200, 2))))
List((100,3,2), (160,1,3))
scala> println(conditionalFold(List((100,3), (130,3))))
List((100,3,2))
scala> println(conditionalFold(List((160,1), (180,2), (200,2))))
List((160,1,3))