我正在尝试使用以下实现来反转 SML 中的列表
fun reverse x y =
case x of
[] => y
| x::xs => reverse(xs, x::y)
;
我收到的错误消息是难以理解的:
trial.sml:1.6-4.35 Error: case object and rules don't agree [tycon mismatch]
rule domain: 'Z list * 'Z list
object: ('Z list * 'Z list) * 'Y
in expression:
(case (arg,arg)
of (x,y) =>
(case x
of nil => y
| :: <pat> => reverse <exp>))
trial.sml:1.6-4.35 Error: right-hand-side of clause doesn't agree with function result type [tycon mismatch]
expression: 'Z -> _
result type: 'Y list
in declaration:
reverse = (fn arg => (fn <pat> => <exp>))
但是,如果我将签名更改为有趣的反向(x:'一个列表,y:'一个列表)那么它起作用了,为什么会这样?有没有办法写这个,这样我就不需要写类型'一个列表?
x y
与(x,y)
不同。
在定义的第一行
fun reverse x y =
您似乎正在尝试编写类型的柯里函数
fn: a' list -> a' list -> 'a list
但在递归调用中
reverse(xs, x::y)
您正在对待reverse
就好像它是和类型的非柯里函数
fn: a' list * a' list -> 'a list
问题与是否添加类型注释完全无关,而是与放置括号(和逗号,如果有的话)有关。有两个有效的修复程序,具体取决于您希望的类型是什么。由于这似乎是家庭作业(没有明显的非家庭作业理由来避免内置rev
),我将把细节留给你。