SML代码语法错误咨询:LET被替换为RAISE及需插入LET的问题排查
排查SML函数中的语法错误
我来帮你理清代码里的两个语法问题,都是因为没严格遵循SML的let-in-end结构规范导致的:
问题1:未绑定的条件表达式
在你的let块开头,这行代码:
if m = 1 orelse m = 2 then y - 1 else y
是一个独立的表达式,但SML要求let的声明区域(in之前的部分)只能放声明语句(比如val变量绑定、fun函数定义),不能直接丢一个没绑定到变量的表达式。看起来你是想计算一个调整后的年份值,但没把它赋值给变量,这直接触发了第一个语法错误。
问题2:表达式放错了区域
你在let的声明区域末尾写了:
rez - lastSmaller(rez - 100000, reductions)
这是一个需要执行的计算表达式,它应该放在in和end之间的执行区域,而不是in之前的声明区域,这就是第二个语法错误的根源。
修正后的代码
下面是调整后的完整代码,我标注了关键修改点:
fun firstNewMoonInt ((d, m, y) : int * int * int) : int option = let (* 修改1:把年份调整表达式绑定到变量,符合声明区域的要求 *) val adjustedYear = if m = 1 orelse m = 2 then y - 1 else y val rez = newStyleCorrection (d, m, y) * 100000 + getNthInt(thousandCorrection, y div 1000) + getNthInt (hundredCorrection, y div 100 mod 10) + getNthInt (decadeCorrection, y mod 100 div 10) + getNthInt (yearCorrection, y mod 1000) + getNthInt (monthCorrection, m - 1) + getNthInt (calendarCorrection, y mod 4) (* 修改2:把最终计算绑定到变量,或者也可以直接放到in之后的执行区域 *) val finalRez = rez - lastSmaller(rez - 100000, reductions) in (* 用绑定后的finalRez做判断,返回结果 *) if finalRez div 100000 <= 30 then SOME finalRez else NONE end
另外也可以更简洁地把最终计算直接放到in之后:
fun firstNewMoonInt ((d, m, y) : int * int * int) : int option = let val adjustedYear = if m = 1 orelse m = 2 then y - 1 else y val rez = newStyleCorrection (d, m, y) * 100000 + getNthInt(thousandCorrection, y div 1000) + getNthInt (hundredCorrection, y div 100 mod 10) + getNthInt (decadeCorrection, y mod 100 div 10) + getNthInt (yearCorrection, y mod 1000) + getNthInt (monthCorrection, m - 1) + getNthInt (calendarCorrection, y mod 4) in val finalRez = rez - lastSmaller(rez - 100000, reductions) if finalRez div 100000 <= 30 then SOME finalRez else NONE end
这样就能解决那两个语法错误啦。
内容的提问来源于stack exchange,提问作者mutter123
相关产品推荐
相关产品推荐

