gpt4 book ai didi

module - Ocaml破坏性替换错误

转载 作者:行者123 更新时间:2023-12-01 11:20:40 26 4
gpt4 key购买 nike

type ('a, 'r) loop
type 'e task
type ('a, 'e) tmpl'

module type COMPONENT =
sig
type t
type event
type r

val update : t -> event -> r
val view : (t, event) tmpl'
end

module type MAIN_COMPONENT =
sig
type t
type event
type r

include COMPONENT
with type t := t
with type event := event
with type r := (t * event task option, r) loop
end

我在尝试替换类型 r 时遇到此错误:

错误:只能替换具有相同参数的类型构造函数。

但是,这是可行的:

module type MAIN_COMPONENT =
sig
type t
type event
type r
type r' = (t * event task option, r) loop

include COMPONENT
with type t := t
with type event := event
with type r := r'
end

为什么?

我怎样才能去掉 r' 类型?

最佳答案

这是破坏性替换的局限性——您只能替换为具有语法相同类型参数的类型构造函数,而不能替换为任意类型表达式。这不是基本限制,因为您可以轻松解决它,如您在示例中所示。

但是,这里存在某种代码重复,您可以通过使用抽象(在类型级别)来摆脱这些重复。在 OCaml 中,您可以使用仿函数来创建类型级抽象,即接受类型和返回类型的函数。语法有点重,但如果选择正确的名称和签名,就可以了。

让我们编写 Loop 抽象,它将根据提供的类型 t1 构造类型 (t1 * t2 task option, t3) loopt2t3:

module type T3 = sig type t1 type t2 type t3 end

module Loop(T : T3) = struct
type t = (T.t1 * T.t2 task option, T.t3) loop
end

鉴于此定义,我们可以使用破坏性替换,因为 F(T).t 是一个没有参数的类型构造函数,例如,

 module type MAIN_COMPONENT = sig
type t
type event
type r

module Types : T3 with type t1 = t
and type t2 = event
and type t3 = r

include COMPONENT
with type t := t
with type event := event
with type r := Loop(Types).t
end

缺点是您需要定义 Types 模块,因为您不能直接在模块签名中的仿函数应用程序中构造模块。

当然,在您的情况下,解决方案比您建议的要大得多,因此,可能最好使用您的解决方案。但是如果你的定义很大,你可以使用仿函数。

关于module - Ocaml破坏性替换错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44049185/

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