提问人:M. Walker 提问时间:3/19/2018 最后编辑:vkurchatkinM. Walker 更新时间:3/19/2018 访问量:144
无法键入多态 [%bs.raw 函数
Unable to type polymorphic [%bs.raw function
问:
1) 有没有办法输入这个?2)有人能够解释这些错误消息吗?
let identity1: 'a => 'a = [%bs.raw {|
function(value) {
return value
}
|}];
/*
Line 2, 11: The type of this expression, '_a -> '_a, contains type variables that cannot be generalized
*/
let identity2: 'a. 'a => 'a = [%bs.raw {|
function(value) {
return value
}
|}];
/*
Line 8, 11: This definition has type 'a -> 'a which is less general than 'a0. 'a0 -> 'a0
*/
答:
5赞
octachron
3/19/2018
#1
bs.raw
是有效的(准确地说是扩展性的),因此它受值限制的约束:http://caml.inria.fr/pub/docs/manual-ocaml/polymorphism.html#sec51 。
简而言之,函数应用程序的结果类型不能泛化,因为它可能已经捕获了一些隐藏的引用。例如,考虑以下函数:
let fake_id () = let store = ref None in fun y ->
match !store with
| None -> y
| Some x -> store := Some x; y
let not_id = fake_id ()
let x = not_id 3
那么下一个应用将是 .因此,的类型不能是 。这就是为什么类型检查器会为您的函数推断类型(使用 4.06 表示法)。此类型不是多态类型,而是尚未知的混凝土类型的占位符。not_id
3
not_id
∀'a. 'a -> 'a
'_weak1 -> '_weak1
_weak1
在正常设置中,解决方案是使用 η 展开来创建一个值:not_id
let id x = fake_id () x
(* or *)
let id: 'a. 'a -> 'a = fun x -> fake_id () x
评论