我试图制作这个非常简单的 SML 函数的尾递归版本:
fun suffixes [] = [[]]
| suffixes (x::xs) = (x::xs) :: suffixes xs;
在此过程中,我在参数上使用了类型注释。下面的代码显示了这一点,并导致类型错误(如下所示),而如果我只是删除类型注释,SML 会毫无问题地接受它,为整个函数提供与上面更简单的函数相同的签名。
fun suffixes_tail xs =
let
fun suffixes_helper [] acc = []::acc
| suffixes_helper (x::xs:'a list) (acc:'b list) =
suffixes_helper xs ((x::xs)::acc)
in
suffixes_helper xs []
end;
错误:
$ sml typeerror.sml
Standard ML of New Jersey v110.71 [built: Thu Sep 17 16:48:42 2009]
[opening typeerror.sml]
val suffixes = fn : 'a list -> 'a list list
typeerror.sml:17.81-17.93 Error: operator and operand don't agree [UBOUND match]
operator domain: 'a list * 'a list list
operand: 'a list * 'b list
in expression:
(x :: xs) :: acc
typeerror.sml:16.13-17.94 Error: types of rules don't agree [UBOUND match]
earlier rule(s): 'a list * 'Z list list -> 'Z list list
this rule: 'a list * 'b list -> 'Y
in rule:
(x :: xs : 'a list,acc : 'b list) =>
(suffixes_helper xs) ((x :: xs) :: acc)
/usr/local/smlnj-110.71/bin/sml: Fatal error -- Uncaught exception Error with 0
raised at ../compiler/TopLevel/interact/evalloop.sml:66.19-66.27
给出了两个错误。后者在这里似乎不太重要,suffixes_helper 的两个子句不匹配。第一个是我不明白的。我注释说第一个参数是 type 'a:list
,第二个参数是 type 'b:list
。'b:list
Hindley-Milner 类型推理算法不应该是建立在我理解的一般统一之上的,能够'a:list list
使用 的替换来统一'b ---> 'a list
吗?
编辑:答案表明它可能与不允许推断类型的类型推断算法有关,从某种意义上说,推断类型比类型注释给出的更严格。我猜想这样的规则只适用于参数和整个函数的注释。我不知道这是否正确。无论如何,我尝试将类型注释移动到函数体,我得到了同样的错误:
fun suffixes_helper [] acc = []::acc
| suffixes_helper (x::xs) acc =
suffixes_helper (xs:'a list) (((x::xs)::acc):'b list);
现在的错误是:
typeerror.sml:5.67-5.89 Error: expression doesn't match constraint [UBOUND match]
expression: 'a list list
constraint: 'b list
in expression:
(x :: xs) :: acc: 'b list