SML函数报错:子句右侧与函数结果类型不匹配原因咨询
错误原因分析与修正
你的函数lst_con预期返回int list(所有常量的列表),但代码里的几个分支都存在类型不匹配的问题:
- Negate分支:
lst_con e2返回的是int list,但你用~运算符对它取反——~只能作用于int类型,不能作用于列表。另外,就算忽略取反的问题,[~ (lst_con e2)]会把结果包装成int list list,和函数返回的int list类型不符。 - Add/Multiply分支:
lst_con e1已经是int list,你用[(lst_con e1)]把它套成了int list list,两个这样的列表拼接后结果还是int list list,同样和预期的int list类型冲突。
修正后的代码
如果你的需求是收集所有常量(不管Negate的影响),代码应该改成这样:
fun lst_con e = case e of Constant i => [i] | Negate e2 => lst_con e2 | Add(e1, e2) => lst_con e1 @ lst_con e2 | Multiply(e1, e2) => lst_con e1 @ lst_con e2
如果你的需求是对Negate表达式里的常量取反后收集,那Negate分支需要用map来处理每个元素:
fun lst_con e = case e of Constant i => [i] | Negate e2 => map ~ (lst_con e2) | Add(e1, e2) => lst_con e1 @ lst_con e2 | Multiply(e1, e2) => lst_con e1 @ lst_con e2
内容的提问来源于stack exchange,提问作者Scentless Apprentice
相关产品推荐
相关产品推荐

