0

I am doing a programming assignment with SML. One of the functions requires me to return a list of triple tuples of ints ( (int * int * int) list ) use to other lists. The function sorts through dates and months to see if any of them coincide, if they do, then they add it to the list. Here is the code for that.

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)

Using this code works to a point, however the function returns an (int * int * int) list list, instead of a (int * int * int) list. I think the problem lies with the then [] statement. Any help would be appreciated.

sshine
  • 15,635
  • 1
  • 41
  • 66
Sloth
  • 65
  • 1
  • 6

1 Answers1

3

The problem is not the then [], the problem lies here:

dates_in_month(dates, hd months) ::
dates_in_months(dates, tl months)

Here you take the result of dates_in_month(dates, hd months), which is a list, and use it as the first argument to ::. As you know, h :: t produces a list whose first element is h. So in this case you create a list whose first element is a list. That is you're creating a list of lists.

Since you don't want that, you shouldn't use ::. You can use @, which takes two lists as its operands and concatenates them. So while [1,2] :: [3,4] :: [] would produce [[1,2], [3,4]], [1,2] @ [3,4] @ [] will produce [1,2,3,4], which is what you want.

sepp2k
  • 363,768
  • 54
  • 674
  • 675
  • Wow, thanks for the quick response! Looking back at the programming assignment the teacher mentioned the '@' operator. I guess I should learn to read, eh? Thank you for saving my grade! – Sloth Jan 24 '13 at 19:16