Skip to content

Instantly share code, notes, and snippets.

@longdog
Last active June 30, 2021 11:55
Show Gist options
  • Save longdog/a14201b9c271284ab8a3d2550fddaa18 to your computer and use it in GitHub Desktop.
Save longdog/a14201b9c271284ab8a3d2550fddaa18 to your computer and use it in GitHub Desktop.
Programming Languages, Part A, Week 2, hw1
(* 1 *)
fun is_older(d1: (int*int*int), d2: (int*int*int)) =
if (#1 d1) < (#1 d2)
then true
else if (#1 d1) > (#1 d2)
then false
else if (#2 d1) < (#2 d2)
then true
else if (#2 d1) > (#2 d2)
then false
else if (#3 d1) < (#3 d2)
then true
else false
(* 2 *)
fun number_in_month(ds: (int*int*int) list, m: int) =
if null ds
then 0
else
let
val d = hd ds
in
if (#2 d) = m
then 1+number_in_month(tl ds, m)
else number_in_month(tl ds, m)
end
(* 3 *)
fun number_in_months(ds: (int*int*int) list, ms: int list) =
if null ms
then 0
else
let
val m = hd ms
in
number_in_month(ds, m) + number_in_months(ds, tl ms)
end
(* 4 *)
fun dates_in_month(ds: (int*int*int) list, m: int) =
if null ds
then []
else
if #2 (hd ds) = m
then
(hd ds)::dates_in_month((tl ds),m)
else
dates_in_month((tl ds),m)
(* 5 *)
fun dates_in_months(ds: (int*int*int) list, ms: int list) =
if null ms
then []
else
dates_in_month(ds, (hd ms)) @ dates_in_months(ds, (tl ms))
(* 6 *)
fun get_nth(ss: string list, n: int) =
if null ss
then ""
else if n = 1
then hd ss
else get_nth((tl ss),n-1)
(* 7 *)
fun date_to_string(d:(int*int*int)) =
let
val months = ["January", "February", "March", "April",
"May", "June", "July", "August", "September", "October", "November", "December"]
in
get_nth(months, (#2 d)) ^ " " ^ Int.toString (#3 d) ^ ", " ^ Int.toString (#1 d)
end
(* 8 *)
fun number_before_reaching_sum(sum: int, ns:int list) =
if sum <= 0
then ~1
else
1+number_before_reaching_sum(sum-(hd ns), (tl ns))
fun number_before_reaching_sum(sum: int, ns:int list) =
if sum <= 0
then ~1
else
1+number_before_reaching_sum(sum-(hd ns), (tl ns))
fun what_month(d: int) =
let
val mnts = [31,28,31,30,31,30,31,31,30,31,30,31]
in
1+number_before_reaching_sum(d, mnts)
end
fun month_range(day1:int, day2:int) =
if day1 > day2
then []
else
what_month(day1)::month_range(day1+1, day2)
fun oldest(ds: (int*int*int) list) =
if null ds
then NONE
else
let
val d1 = hd ds
val d2 = oldest((tl ds))
in
if isSome d2 andalso is_older((valOf d2), d1)
then d2
else SOME(d1)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment