【发布时间】:2017-10-20 03:14:37
【问题描述】:
我想知道在 scala 中解决这个问题的惯用方法。
给定一个开始日期和一个结束日期以及介于两者之间的日期集合,确定给定的日期集合是否包含从开始日期到结束日期所需的所有日期,并且两者之间没有间隔日期。
类型签名:
def checkDate(start: DateTime, end: DateTime, between: IndexedSeq[DateTime]): Boolean
执行此操作的“正常”或“无效”方式如下:
def checkDate(start: DateTime, end: DateTime, between: IndexedSeq[DateTime]): Boolean = {
i = 1
status = true
while(start != end) {
d = start.plusDays(i)
if (!between.contains(d) {
status = false
break
}
i += 1
}
return status
}
如何使用折叠来做到这一点?
到目前为止,这是我的思考过程:
def checkDate(start: DateTime, end: DateTime, between: IndexedSeq[DateTime]): Boolean = {
// A fold will assume the dates are in order and move left (or right)
// This means the dates must be sorted.
val sorted = between.sortBy(_.getMillis())
val a = sorted.foldLeft(List[Boolean]) {
(acc, current) => {
// How do I access an iterable version of the start date?
if (current == ??) {
acc :: true
} else false
}
}
// If the foldLeft produced any values that could NOT be matched
// to the between list, then the start date does not have an
// uninterrupted path to the end date.
if (a.count(_ == false) > 0) false
else true
}
我只需要弄清楚如何索引 start 参数,这样我就可以在 fold 遍历 between 集合时增加它的值。或者,折叠可能根本不是我应该使用的。
任何帮助将不胜感激!
【问题讨论】:
-
如果您需要在遍历整个集合之前停止循环,折叠将无济于事(您可以抛出异常以停止进一步处理,但是,恕我直言,这是不好的方法)。你应该使用尾递归。
-
@ArtavazdBalayan 对。 Scala 对
Exception很不利;我很高兴看到的一个特性不是从 Java 继承来的。 -
您可以将
return status替换为status。return仅在需要进行非本地退出时才需要,并且在 Scala 中很少使用。许多 Scala 程序员从不使用return。