如何确定一年的哪一天属于哪个月?

问题描述:

我是一名初学者,我必须在SML中编写一个函数。

I'm a beginner and I gotta write a function in SML.

赋值问题是:

The assignment question is :


编写一个名为 what_month 将每天的数字(例如257,假定一年365天)作为输入,并返回当天所属的月份数。

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.

示例: what_month(40)应返回 2 (二月)。

Example: what_month(40) should return 2 (February).


对于简单的情况(不包含闰年),您可以定义以$ months_days 和递归辅助函数 aux 为单位的天数列表,其中 int 称为 sum 和一个 int list 称为 numbers ,并返回一个 int n ,这样第一个 n 元素添加到 sum ,但第一个 n + 1 元素list添加到 sum 或更多。

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