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