Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/sorting/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ocaml 使用ref单元的动态绑定_Ocaml - Fatal编程技术网

Ocaml 使用ref单元的动态绑定

Ocaml 使用ref单元的动态绑定,ocaml,Ocaml,我知道你不能这么做,但我想知道确切的原因 module M : sig type 'a t val call : 'a t -> 'a option end = struct type 'a t let state : ('a t -> 'a option) ref = ref (fun _ -> None) let call : ('a t -> 'a option) = fun x -> !state x end 结果: Error:

我知道你不能这么做,但我想知道确切的原因

module M : sig 
  type 'a t
  val call : 'a t -> 'a option
end = struct 
  type 'a t
  let state : ('a t -> 'a option) ref = ref (fun _ -> None)
  let call : ('a t -> 'a option) = fun x -> !state x
end
结果:

Error: Signature mismatch:
Modules do not match:
    sig 
        type 'a t
        val state : ('_a t -> '_a option) ref
        val call : '_a t -> '_a option
    end
is not included in
    sig 
        type 'a t 
        val call : 'a t -> 'a option 
    end

    Values do not match:
        val call : '_a t -> '_a option
    is not included in
        val call : 'a t -> 'a option
为什么这里的抽象类型不兼容


我的直觉告诉我它与早期绑定和后期绑定有关,但我正在寻找类型系统在这里做什么的确切描述

一种看待它的方法是,您的字段
状态
不能具有您赋予它的多态值,因为可变值不能是多态的。引用最多是单态的(如类型变量的
'\u a
符号所示)

如果您只是尝试在顶层声明一个类似的引用,您将看到相同的效果:

# let lfr: ('a list -> 'a option) ref = ref (fun x -> None);;
val lfr : ('_a list -> '_a option) ref = {contents = <fun>}
以下代码使用
lfrec
而不是引用为我编译:

module M : sig
  type 'a t
  val call : 'a t -> 'a option
end = struct
  type 'a t
  type lfrec = { mutable f: 'a. 'a t -> 'a option }
  let state: lfrec = { f = fun _ -> None }
  let call : ('a t -> 'a option) = fun x -> state.f x
end

啊,不知道,"a","a","code"是单音型的。非常感谢。同时也感谢你提供了这篇文章的链接。我认为你可以使用秩2多态性来获得你想要的行为。请参阅更新。我刚刚将字符
'a'b.
添加到我一直在处理的内容()中,并节省了工作天数。非常感谢。
module M : sig
  type 'a t
  val call : 'a t -> 'a option
end = struct
  type 'a t
  type lfrec = { mutable f: 'a. 'a t -> 'a option }
  let state: lfrec = { f = fun _ -> None }
  let call : ('a t -> 'a option) = fun x -> state.f x
end