Types 为什么为我的ML函数推断的类型与我预期的不同?

Types 为什么为我的ML函数推断的类型与我预期的不同?,types,type-inference,ml,Types,Type Inference,Ml,我制作的函数名为maptree。下面是我的代码: datatype 'a tree = LEAF of 'a | NODE of 'a tree * 'a tree; fun maptree(f, NODE(X, Y)) = NODE(maptree(f, X), maptree(f, Y)) | maptree(f, LEAF(X)) = LEAF(f X); 我希望maptree具有该类型 ('a -> 'a) -> 'a tree -> 'a tree 但是编译器推

我制作的函数名为
maptree
。下面是我的代码:

datatype 'a tree = LEAF of 'a | NODE of 'a tree * 'a tree;
fun maptree(f, NODE(X, Y)) = NODE(maptree(f, X), maptree(f, Y))
| maptree(f, LEAF(X)) = LEAF(f X);
我希望maptree具有该类型

 ('a -> 'a) -> 'a tree -> 'a tree
但是编译器推断的类型是

 ('a -> 'b) * 'a tree -> 'b tree
为什么会发生这种情况?

类型推断算法允许您获得比预期更通用的类型

当算法试图推断
maptree
的类型时,它假定
f:'a->'b
(根据您将
f
用作函数的事实)。没有任何东西进一步限制
f
的类型

例如,如果您将
maptree
函数定义如下(我在
LEAF
案例中使用了
f
两次):

然后,类型推断机制必须将
f
的类型限制为
'a->'a
(因为我们将函数的输出输入)

修改案例的SML/NJ输出:

val maptree = fn : ('a -> 'a) * 'a tree -> 'a tree
val maptree = fn : ('a -> 'a) * 'a tree -> 'a tree