gpt4 book ai didi

ocaml - 为什么在一流的模块包装中禁用破坏性替换?

转载 作者:行者123 更新时间:2023-12-04 04:05:19 24 4
gpt4 key购买 nike

假设这些:

module type Foo = sig
type t
val foo : t -> t
end

module M = struct
type t = int
let foo t = t + 1
end

然后我做:
module type Goo = Foo with type t = int

module type Hoo = Foo with type t := int

let x = (module M : Goo) (* correct *)

let y = (module M : Hoo) (* correct *)

let z = (module M : Foo with type t = int) (* correct *)

最重要的是正确,没问题。

但是,如果我这样做
let z = (module M : Foo with type t := int) (* wrong *)

这是错误的,并且给出了错误

Error: Parse error: "=" expected after [ident] (in [package_type_cstr])



为什么我不能使用 :=在一流的模块包装中?

最佳答案

在 OCaml 4.01 和更早的版本中,第一类模块是主格类型的。换句话说,它们的类型是基于使用的模块类型的名称,而不是它的结构。例如:

        OCaml version 4.01.0

# module type T = sig type t end;;
module type T = sig type t end
# module type S = sig type t end;;
module type S = sig type t end
# let f (x : (module T)) : (module S) = x;;
Characters 38-39:
let f (x : (module T)) : (module S) = x;;
^
Error: This expression has type (module T)
but an expression was expected of type (module S)

这要求模块类型有一个名称:
# type t = (module sig type t end);;
Characters 17-20:
type t = (module sig type t end);;
^^^
Error: Syntax error

不允许破坏性替换,因为它会创建一个没有名称的新模块类型。常规替换很好,因为 S with type t = int , 仍然是 S ,我们只是更了解它的定义。 S with type t := int不是 S它与 S 有不同的组成部分因为它缺少 t类型。

最近( MantisSVN ),第一类模块的类型检查已更改为结构性而不是主格:
        OCaml version 4.02.0+dev5-2014-04-29

# module type T = sig type t end;;
module type T = sig type t end
# module type S = sig type t end;;
module type S = sig type t end
# let f (x : (module T)) : (module S) = x;;
val f : (module T) -> (module S) = <fun>

这意味着可以为没有名称的类型创建一流的模块。但是,这还没有完成,在 4.02 中将不可用。因此,在 4.02 之后的版本中,确实可以在一流的模块类型中使用破坏性替换。

关于ocaml - 为什么在一流的模块包装中禁用破坏性替换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23546475/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com