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

纵然是瞬间 提交于 2020-03-23 09:03:28

问题


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?


回答1:


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'    



回答2:


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).



来源:https://stackoverflow.com/questions/60402276/number-in-month-exercise-error-in-sml-function-to-build-a-list-of-integers-from

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!