이 문제를 스칼라로 접근하는 관용적 인 방법을 알고 싶습니다.폴드 할 부울 테스트를 사용하는 방법
시작 날짜와 종료 날짜와 그 사이에 날짜 모음이 있으면 지정된 날짜 모음에 간격 날짜가없는 시작 날짜부터 끝 날짜까지 필요한 모든 날짜가 포함되어 있는지 확인하십시오.
유형 서명 :
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
}
난 그냥 내가 수집 사이에 걸쳐 배 반복으로의 가치를 높일 수 있습니다 인덱스 시작 매개 변수를하는 방법을 알아낼 필요가있다. 또는 접는 것이 내가 사용하기로되어있는 것이 아닐 수도 있습니다.
도움이 될 것입니다.
sortedBetween.sliding(2).forall {
case List(prev,cur) => ..do the check here ..
}
또한
, 당신의 결과를 ingnoring 참고 :
val a = sortedBetween.foldLeft((List[Boolean](), start)) {
case ((results, prev), current) => {
... calculate res here ...
(results ++ List(res), current)
}
}
을하지만 이런 종류의 더 나은 슬라이딩 사용 및 조합 FORALL을 확인하십시오
(추가 처리를 중지하도록 예외를 던질 수 있지만, 이럴, 나쁜 방법). 꼬리 재귀와 함께 가야합니다. –
@ArtavazdBalayan 맞아. 스칼라는 매우 예외적이다. 내가보기에 기쁘다는 특성은 Java에서 상속받지 않았다. – franklin
'return status'를 단지'status'로 바꿀 수 있습니다. 'return'은 비 - 지역 출구가 필요한 경우에만 필요하며 Scala에서는 거의 사용되지 않습니다. 많은 스칼라 프로그래머는 그대로'return'을 사용하지 않습니다. –