首页 > 解决方案 > Scala中的联合日期范围

问题描述

假设我有一个日期范围元组列表,那么组合和减少它们的最优雅和最有效的方法是什么?

例如,以下列表:

('2021-01-10', '2021-01-15')
('2021-01-13', '2021-01-17')
('2021-01-25', '2021-01-30')
('2021-01-17', '2021-01-20')
('2021-02-17', '2021-02-20')

输出应该是:

('2021-01-10','2021-01-20')
('2021-01-25','2021-01-30')
('2021-02-17', '2021-02-20')

谢谢

标签: scalafunctional-programming

解决方案


这个怎么样?

type LIST = List[(String, String)]

def mergeDates(list: LIST): LIST = {
  @annotation.tailrec
  def loop(l: LIST, curr: (String, String), res: LIST): LIST =
    l match {
      case hd::tail =>
        if (hd._1 <= curr._2) {
          loop(tail, (curr._1, hd._2), res)
        } else {
          loop(tail, hd, curr +: res)
        }
      case _ =>
        (curr +: res).reverse
    }

  list.sortBy(_._1) match {
    case hd::tail => loop(tail, hd, Nil)
    case _ => Nil
  }
}

mergeDates(list).foreach(println)

这是有效的,因为这种格式的日期字符串按日期顺序正确排序。如果允许更通用的日期格式,则需要做更多的工作。


推荐阅读