hagenek
hagenek

Reputation: 118

number_in_month exercise (Error in SML function to build a list of integers from a list of tuples)

val test1 = [(1,5,3),(3,5,2),(3,4,5)]

fun number_in_month dates_and_month  =
    case dates_and_month of
        (x,y,z)::xs' => y :: number_in_month xs'           

This code produces the following error when I run in the REPL with test1:

uncaught exception Match [nonexhaustive match failure] raised at: hw1pm.sml:28.49

Any clue why?

Upvotes: 2

Views: 102

Answers (2)

sshine
sshine

Reputation: 16105

Edit: I've tried to make this answer more helpful while preserving the observation that this is probably the most asked SML question on StackOverflow. A total list of the times this question was asked: 1st, 2nd, 3rd, 4th, 5th, 6th, 7th, 8th, 9th, 10th, 11th, 12th, 13th, 14th, 15th and 16th (not counting this post).

Rather than to answer this question again, a curated version of those are here:

  • 1st, 2nd, 6th, 12th struggle with recursion and infinite recursion. Some attempts include the use of the function null, and others include pattern matching. I'd go with the recommendation to use pattern matching.
  • 3rd, 4th, 5th, 7th, 13th, 14th provide a lot of insight into the general structure of this function. You'll probably learn a bunch more than you asked for by just reading those answers, and since they cover a lot of elementary subjects in the context of a function you're actively working with, this may be very worthwhile.
  • 10th deals with using a mutable reference, so stay away from that one unless you're about to make that same mistake!
  • 11th doesn't actually ask anything, but the author says they have this exercise and then kind of stops dead in their tracks. There's a lesson here and I'm not going to be the one to figure it out.
  • 8th, 9th, 15th and 16th appear to address syntax errors.

Questions asked on this matter subsequent to this answer: 17th (missing else).

Upvotes: 0

hagenek
hagenek

Reputation: 118

It did not know what do when the list was empty.

Working code:

fun number_in_month dates_and_month  =
    case dates_and_month of
        [] => []
        | (x,y,z)::xs' => y :: number_in_month xs'    

Upvotes: 2

Related Questions