gpt4 book ai didi

compiler-errors - 解压受类型变量约束的一流模块

转载 作者:行者123 更新时间:2023-12-02 10:45:01 25 4
gpt4 key购买 nike

我正在尝试编写一个基本上如下所示的函数:

module type M = sig
type t
val doStuff : t -> unit
end

let f : 'a. 'a -> (module M with type t = 'a) -> unit
= fun value (module MSomething) -> MSomething.doStuff value

也就是说,一个接受任何类型值的函数,以及一个包含一个或多个可以对该值进行操作的函数的关联模块。不幸的是,上面会让编译器提示

The type of this packed module contains variables



但是,我发现如果我将它包装在 1) 生成 'a 的 GADT 中,我仍然可以让它工作。存在和 2) 提供从另一个参数化类型变量到存在的转换器:

type 'b gadt =
GADT: ('b -> 'a) * (module M with type t = 'a) -> 'b gadt

let f value (GADT (convert, (module MSomething))) =
MSomething.doStuff (convert value)

GADT 本身并不令人讨厌1, 但我非常想避免 convert函数,因为它除了帮助编译器之外没有任何用途。 这有可能吗?

完整示例/MCVE

module type M = sig
type t
val doStuff : t -> unit
end

module MInt = struct
type t = int
let doStuff = print_int
end

let f : 'a. 'a -> (module M with type t = 'a) -> unit
= fun value (module MSomething) -> MSomething.doStuff value

let () = f 42 (module MInt : M with type t = int)
let () = print_newline ()

1 我实际上想要 GADT,因为我需要用不同的存在参数对模块进行参数化,这样我就可以将不同类型的模块放在一个列表中。但为简单起见,我从上面的第一个示例中省略了这一点。

最佳答案

对于一流的模块(如任何本地模块),您应该使用本地抽象类型而不是显式的多态注释:

let f (type a) (value:a) (module M: M with type t = a) = M.doStuff value

工作得很好。

关于compiler-errors - 解压受类型变量约束的一流模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58342691/

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