You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SMLNJ中‘syntax error found at EOF’错误含义及递归函数报错原因咨询

我来帮你搞定这个SML/NJ的语法错误问题!

解读Error: syntax error found at EOF错误

首先,这个错误的字面意思是:编译器读到输入的末尾(EOF,End Of File)时,发现代码存在语法不完整的问题——简单说就是你写的代码没写完,还有未闭合的语法结构,编译器等不到它需要的结尾部分,就报错了。

你的代码触发错误的原因

看你写的递归函数:

fun number_in_month (dates : int*int*int list, month : int) = if null dates then 0 else if #2 (hd dates) = month then number_in_month(tl dates, month) + 1

SML里的if是表达式,不是语句,所以必须同时包含then和else两个分支,缺一不可。你的代码里:

  • 第一个if null dates then 0是完整的(有then和else)
  • 但第二个if #2 (hd dates) = month then ...只写了then分支,完全没写else分支——当当前日期的月份不等于目标月份时,编译器不知道该执行什么逻辑,代码读到末尾也没补全这个分支,所以就触发了EOF的语法错误。
修正后的代码

你需要补充else分支,处理“当前日期月份不匹配”的情况——此时直接递归处理剩余列表即可:

fun number_in_month (dates : int*int*int list, month : int) = 
    if null dates then 0 
    else if #2 (hd dates) = month then number_in_month(tl dates, month) + 1
    else number_in_month(tl dates, month)

这样整个if-else结构就完整了:

  1. 如果日期列表为空,返回0
  2. 如果列表第一个日期的月份匹配,递归处理剩余列表并加1
  3. 如果不匹配,直接递归处理剩余列表(相当于计数不增加)
测试例子

比如调用:

number_in_month([(2023, 10, 5), (2023, 10, 15), (2023, 11, 20)], 10)

会返回2,完全符合你的预期。

内容的提问来源于stack exchange,提问作者deppep

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 19:42:47