问题
I am trying to learn SML, and I am trying to implement two functions. The first function works fine, but when I added the second function it gives me an run-time error:
stdIn:1.2-1.17 Error: unbound variable or constructor: number_in_month
This happens while calling the function number_in_month. My code is:
fun is_older(d1 :int*int*int,d2 :int*int*int) =
(#1 d1) < (#1 d2) andalso (#2 d1) < (#2 d2) andalso (#3 d1) < (#3 d2)
fun number_in_month(da :(int * int * int) list ,mo : int) =
if da = []
then 0
else if (#2(hd da)) = mo
then 1 + number_in_month((tl da),mo)
else 0 + number_in_month((tl da),mo)
回答1:
Your question sounds surprisingly much like these other questions: SML list iteration (8 months ago), recursion in SML (9 months ago), and Count elements in a list (8 months ago), so you certainly don't get points for asking a creative question.
Some of the questions above have been answered extensively. Look at them.
Here is your code rewritten in a better style:
(* Find better variable names than x, y and z. *)
fun is_older ((x1,y1,z1), (x2,y2,z2)) =
x1 < x2 andalso y1 < y2 andalso z1 < z2
fun number_in_month ([], mo) = 0
| number_in_month ((x,y,z)::rest, mo) =
if y = mo then 1 + number_in_month(rest, mo)
else 0 + number_in_month(rest, mo)
来源:https://stackoverflow.com/questions/19398097/number-in-month-exercise-sml-error-unbound-variable