问题
(* Write a function number_in_month that takes a list of dates and a month (i.e., an int) and returns how many dates in the list are in the given month.*)
fun number_in_month(datelist : (int*int*int) list, month : int) =
if null(tl (datelist))
then if #2(hd (datelist)) = month then 1 else 0
else if #2(hd (datelist)) = month
then 1 + number_in_month(tl datelist, month)
else number_in_month(tl datelist, month)
(* Write a function number_in_months that takes a list of dates and a list of months (i.e., an int list) and returns the number of dates in the list of dates that are in any of the months in the list of months. Assume the list of months has no number repeated. Hint: Use your answer to the previous problem. *)
fun number_in_months(datelist : (int*int*int) list, monthlist : int list)
if null(tl (monthlist))
then number_in_month(datelist, hd monthlist)
else number_in_month(datelist, hd monthlist)
+ number_in_months(datelist, tl monthlist)
The second function gives me this error when I try to compile it:
hw1.sml:42.5 Error: syntax error: inserting EQUALOP
[unexpected exception: Compile]
uncaught exception Compile [Compile: "syntax error"]
raised at: ../compiler/Parse/main/smlfile.sml:19.24-19.46
../compiler/TopLevel/interact/evalloop.sml:45.54
../compiler/TopLevel/interact/evalloop.sml:306.20-306.23
../compiler/TopLevel/interact/interact.sml:65.13-65.16
-
-
回答1:
"syntax error: inserting EQUALOP" means that SML is expecting a =
character.
The error messages from SML/NJ is one of the things that haven't improved one bit over the past twenty years. They often report what the parser does in order to try to recover from an error rather than what the error might be.
List recursion (and most everything else) is much nicer to write with pattern matching than with conditionals and selectors:
fun number_in_month ([], _) = 0
| number_in_month ((_, m, _)::ds, m') = (if m = m' then 1 else 0) + number_in_month(ds, m');
fun number_in_months (_, []) = 0
| number_in_months (ds, m::ms) = number_in_month(ds, m) + number_in_months(ds, ms);
This also lets SML let you know when you have forgotten a case, for instance the case of the empty list (which you forgot about).
回答2:
Answer: Forgot the = sign. This is correct:
fun number_in_months(datelist : (int*int*int) list, monthlist : int list) =
if null(tl (monthlist))
then number_in_month(datelist, hd monthlist)
else number_in_month(datelist, hd monthlist)
+ number_in_months(datelist, tl monthlist)
来源:https://stackoverflow.com/questions/60157435/number-in-month-exercise-getting-equal-op-error-in-sml-one-function-works-oth