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

如何检查值x是否存在于列表中?SML代码编译报错求助

修复SML列表存在性检查函数的语法错误

原代码

fun exist [] x = false
  | exist l::ls x = x=l orelse exist ls x

编译错误

Error: infix operator "::" used without "op" in fun dec
Error: clauses don't all have same number of patterns
Error: data constructor :: used without argument in pattern
Error: types of rules don't agree [tycon mismatch]
earlier rule(s): 'Z list * 'Y -> bool
this rule: ''X * 'W * 'V * ''X -> bool
in rule:
(l,_,ls,x) => (x = l) orelse ((exist ls) x)

修改方案

问题出在模式匹配的语法格式上,第二个子句中的l::ls没有用括号包裹,导致SML错误解析参数结构。只需给l::ls加上括号即可:

fun exist [] x = false
  | exist (l::ls) x = x = l orelse exist ls x

错误原因说明

SML的函数子句中,若要将::作为列表构造器用于模式匹配,必须把整个模式l::ls放在括号里。原代码无括号时,SML会误将exist l::ls x解析为(exist l) :: (ls x),把::当成了独立的中缀运算符,进而引发参数数量不匹配、类型不兼容等一系列错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 18:44:56