Day of the week: Difference between revisions

(Added Bracmat example)
Line 2,164:
[[Category:Scala Implementations]]
{{libheader|Scala}}
===JDK (discouraged) ===
<lang scala>import java.util.{ Calendar, GregorianCalendar }
import Calendar.{ DAY_OF_WEEK, DECEMBER, SUNDAY }
Line 2,170:
object DayOfTheWeek extends App {
val years = 2008 to 2121
 
val yuletide = for {
year <- years
ifyears.filter(year => (new GregorianCalendar(year, DECEMBER, 25)).get(DAY_OF_WEEK) == SUNDAY)
 
} yield year
// If you want a test: (optional)
assert(yuletide ==
Seq(2011, 2016, 2022, 2033, 2039, 2044, 2050, 2061,
2067, 2072, 2078, 2089, 2095, 2101, 2107, 2112, 2118))
 
println(yuletide.mkString(
s"${yuletide.count(p => true)length} Years between ${years.head} and ${years.last}" +
" including where Christmas is observed on Sunday:\n", ", ", "."))
}</lang>
===JDK >= 8 (recommended)===
====Naive programming====
<lang scala>import java.time.{ DayOfWeek, LocalDate }
 
Line 2,193 ⟶ 2,198:
" including where Christmas is observed on Sunday:\n", ", ", "."))
}</lang>
====Idiomatic programming====
<lang scala>import java.time.{ DayOfWeek, LocalDate }
 
object DayOfTheWeek2DayOfTheWeek1 extends App {
val years = 2008 to 2121
val yuletide =
years.filter(yryear => (LocalDate.of(yryear, 12, 25).getDayOfWeek() == DayOfWeek.SUNDAY))
 
// If you want a test: (optional)
assert(yuletide ==
Seq(2011, 2016, 2022, 2033, 2039, 2044, 2050, 2061,
2067, 2072, 2078, 2089, 2095, 2101, 2107, 2112, 2118))
 
println(yuletide.mkString(
s"${yuletide.count(p => true)length} Years between ${years.head} and ${years.last}" +
" including where Christmas is observed on Sunday:\n", ", ", "."))
}</lang>
====Tail recursion version====
<lang scala>import java.time.{ DayOfWeek, LocalDate }
import scala.annotation.tailrec
Line 2,216 ⟶ 2,226:
if (anni == Nil) accu
else inner(anni.tail, accu ++
(if (LocalDate.of(anni.head, 12, 25).getDayOfWeek() == DayOfWeek.SUNDAY) List(anni.head)
List(anni.head) else Nil))
}
inner(years.toList, Nil)
}
 
// If you want a test: (optional)
assert(yuletide ==
Seq(2011, 2016, 2022, 2033, 2039, 2044, 2050, 2061,
2067, 2072, 2078, 2089, 2095, 2101, 2107, 2112, 2118))
 
println(yuletide.mkString(
s"${yuletide.count(p => true)length} Years between ${years.head} and ${years.last}" +
" including where Christmas is observed on Sunday:\n", ", ", "."))
}</lang>
Anonymous user