无法键入多态 [%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
*/

https://reasonml.github.io/en/try.html?reason=FAGwpgLgBAlgJmAdhGECeBGAXFA5AQygF4A%20PQoqAbQFIAjAZwDoAnfAdygG8AfYKKADMArogDGKAPaIAFADd8IYWACU3fgKgtIwloigKlYDQF9gPEwF0A3MGAB6AFTAAMjERgoAJgA0UDNhQACoAFp7oAA6ekoJQECEwDFBgAB4R2gwMMNJ%20uAD6hAC0ZPn4fmLSEPjuSZGeCiww%20HTgtSH40GL4iIiS0HSeAOZIYGwgMABeYHDAjvZ24NDwSCjoXjgETOTEJRTU9MxsnLwaIuJSsobKalwaAtoQuvpXxgJmFjZ2Tq7ungAcfgCOFCiSgCEE7lQ2X07VqaCi22K23YCTEIVgSVaSWGHjGcXa%20gIAAYtsSoEjibN5kA

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

那么not_id的下一个应用就是3。因此not_id的类型不能是∀'a. 'a -> 'a。这就是 type-checker 为您的函数推断类型 '_weak1 -> '_weak1 的原因(使用 4.06 表示法)。此类型 _weak1 不是多态类型,而是未知具体类型的占位符。

在正常设置中,解决方案是使 not_id 具有 η 扩展的值:

 let id x = fake_id () x 
 (* or *)
 let id: 'a. 'a -> 'a = fun x -> fake_id () x