问题
I'm a beginner and I gotta write a function in SML.
The assignment question is :
write a function named
what_month
that takes the number of a day (e.g., 257, assuming 365 days a year) as input, and returns the number of the month, that this day belongs to.Example:
what_month(40)
should return2
(February).
回答1:
for the simple case(that doesn't account for leap year), you can define a list of days in months months_days
, and a recursive helper function aux
, that takes an int
called sum
and an int list
called numbers
, and returns an int
n
such that the first n
elements of the list add to less than sum
, but the first n + 1
elements of the list add to sum
or more.
val month_days= [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
fun what_month(day :int) =
let
fun aux(sum :int, numbers: int list) =
let
val numbers_tail = tl numbers
in
if sum <= (hd numbers)
then 1
else
1 + aux(sum, (hd numbers + hd numbers_tail)::(tl numbers_tail))
end
in
aux(day, month_days)
end
回答2:
One way of doing this could be to create a list of how many days there are in each month.
Such a list could look like this
days_in_month = [31, 28, 31, 30, ...]
Then you could easily count down your input number according to how many days each month has. When you reach a number which are smaller than the next months number of days, the input number must belong to the month you had reached.
Beware that this doesn't account for leap year. But that should not bee that difficult to work into it as well, if needed.
来源:https://stackoverflow.com/questions/15787541/how-to-determine-which-day-of-a-year-belongs-to-what-month