use*_*220 3 types functional-programming type-inference ml
考虑函数f1和f2,例如Haskell或ML.假设f2调用f1.类型推断是否仅使用f1可以调用的信息,这相当于只查看f1的定义.或者它也看看f1在f1上进行类型推断时如何调用f1.例如,f2可能在调用f1时传入文字,这会限制f1的参数类型.
这取决于函数f1是通过声明还是通过其他方式(例如作为函数参数f2)绑定.在前一种情况下,它的类型可以推广为多态,后者则不能,并且未解析的部分由上下文决定.即使在前一种情况下,也可能适用其他规则,例如ML的价值限制.
在Haskell中考虑这个例子:
f1 = \x -> x -- polymorphic: f1 :: a -> a
f2 = f1 True -- instantiates f1 :: Bool -> Bool
f2 = let f1 = \x -> x in f1 True -- likewise
f2 = (\f1 -> f1 True) (\x -> x) -- here, f1 cannot be polymorphic,
-- so the lambda is restricted to Bool -> Bool by the call
Run Code Online (Sandbox Code Playgroud)
和SML类似:
val f1 = fn x => x (* polymorphic, f1 : 'a -> 'a *)
val f2 = f1 true
val f2 = let val f1 = fn x => x in f1 true end (* likewise *)
val f2 = (fn f1 => f1 true) (fn x => x) (* f1 monomorphic, f1 : bool -> bool *)
val f1 = let _ = 0 in fn x => x end (* value restriction applies, f1 cannot be polymorphic *)
val f2 = f1 true (* determines type f1 : bool -> bool *)
Run Code Online (Sandbox Code Playgroud)
为清楚起见,我在这里没有使用缩写函数声明语法.