is_older, number_in_month done

This commit is contained in:
Gregory 2020-05-31 18:35:01 +03:00
parent 0ab1762fa1
commit e2648e3cf6
3 changed files with 106 additions and 0 deletions

32
sml/week1/date.sml Normal file
View file

@ -0,0 +1,32 @@
(* year * month * day *)
type Date = int * int * int
fun fold f lst acc =
case lst of
[] => acc
| head::tail => fold f tail (f head acc)
fun is_older (
(y1, m1, d1): Date,
(y2, m2, d2): Date
): bool =
let
val same_dates = y1 = y2 andalso m1 = m2 andalso d1 = d2
val older = y1 <= y2 andalso m1 <= m2 andalso d1 <= d2
in
if same_dates then false else older
end
fun number_in_month (
dates: Date list,
month_to_find: int
): int =
let
fun count_month (_, month, _) occurences =
if month = month_to_find
then occurences + 1
else occurences
in
fold count_month dates 0
end

57
sml/week1/date_tests.sml Normal file
View file

@ -0,0 +1,57 @@
use "test.sml";
use "date.sml";
val () =
assert
(is_older ((1999, 12, 31), (1999, 12, 31)) = false)
"is_older: same dates evaluates to false"
val () =
assert
(is_older ((2000, 11, 28), (2000, 11, 29)) = true)
"is_older: first date older than second by day"
val () =
assert
(is_older ((1999, 12, 31), (1999, 11, 31)) = false)
"is_older: first date greater by month"
val () =
assert
(is_older ((1999, 12, 31), (1999, 11, 31)) = false)
"is_older: first date greater by month"
val () =
assert
(is_older ((2000, 12, 31), (1999, 12, 31)) = false)
"is_older: first date greater by year"
val () =
assert
(number_in_month ([(2000, 12, 31)], 12) = 1)
"number_in_month: one date with exact month"
val () =
let
val dates = [(2000, 12, 31), (2000, 12, 31)]
val month = 12
val expect = 2
in
assert
(number_in_month (dates, month) = expect)
"number_in_month: two date with exact month"
end
val () =
let
val dates = []
val month = 12
val expect = 0
in
assert
(number_in_month (dates, month) = expect)
"number_in_month: empty list"
end
val () = complete ()

17
sml/week1/test.sml Normal file
View file

@ -0,0 +1,17 @@
fun assert condition message =
if condition
then
print (message ^ "\n")
else
let
val () = print ("Assert error: " ^ message ^ "\n")
in
OS.Process.exit OS.Process.failure
end
fun complete () =
let
val () = print "All tests passed!"
in
OS.Process.exit OS.Process.success
end