我正在使用SML进行编程任务。其中一个功能要求我将使用的int三元组列表((int * int * int)list)返回给其他列表。该函数对日期和月份进行排序,以查看它们是否一致,如果一致,则将其添加到列表中。这是该代码。
fun dates_in_month (dates : (int * int * int) list, month : int) =
if null dates
then []
else
if #2 (hd dates) = month
then (hd dates) :: dates_in_month(tl dates, month)
else dates_in_month(tl dates, month)
fun dates_in_months (dates : (int * int * int) list, months : int list) =
if null months orelse null dates
then []
else
dates_in_month(dates, hd months) ::
dates_in_months(dates, tl months)
使用此代码在一定程度上起作用,但是该函数返回一个(int * int * int)列表列表,而不是(int * int * int)列表。我认为问题在于then []
语句。任何帮助,将不胜感激。
问题不是then []
,问题在这里:
dates_in_month(dates, hd months) ::
dates_in_months(dates, tl months)
这里您将dates_in_month(dates, hd months)
的结果作为列表,并将其用作::
的第一个参数。如您所知,h :: t
产生一个列表,其第一个元素为h
。因此,在这种情况下,您将创建一个列表,其第一个元素是列表。那就是您正在创建列表列表。
由于您不想要它,因此不应该使用::
。您可以使用@
,它将两个列表作为其操作数并将它们连接起来。因此,虽然[1,2] :: [3,4] :: []
会产生[[1,2], [3,4]]
,但[1,2] @ [3,4] @ []
会产生[1,2,3,4]
,这就是您想要的。