gpt4 book ai didi

OCaml 坚持函数不是多态的,但不指定类型

转载 作者:行者123 更新时间:2023-12-01 12:49:23 24 4
gpt4 key购买 nike

是否可以显式写出一个非多态但像下划线类型一样延迟统一的类型?

因此,OCaml 在类型检查过程中有时会生成一个类型,在顶层打印时带有前导下划线(例如 _a)。具体来说,这些会在实例化空的 Hashtbl.t 以及其他一些情况下出现。

# Hashtbl.create 1;;
- : ('_a, '_b) Hashtbl.t = <abstr>

但是,用户无法在源代码中显式引用这些类型。

# (5: int);;
- : int = 5
# (5: 'a);;
- : int = 5
# (5: '_a);;
Error: The type variable name '_a is not allowed in programs

您可以利用 OCaml 中缺乏高级多态性的缺陷来创建显式非多态函数

# let id = snd ((), fun y -> y);;
val id : '_a -> '_a = <fun>
# (fun () -> fun y -> y) ();;
- : '_a -> '_a = <fun>

我希望能够做类似的事情

let id : <some magical type> = fun x -> x

并且不依赖于类型系统的限制,这种限制将来可能会消失。

最佳答案

您可以利用引用不可概括的事实。

# let id = let rx = ref [] in fun x -> rx := [x]; rx := []; x;;
val id : '_weak1 -> '_weak1 = <fun>

我认为引用的这个属性不太可能改变。

我假设您想要的是此版本的 id 在第一次实际使用时采用单个单态类型:

# id "yes";;
- : string = "yes"
# id;;
- : string -> string = <fun>

如果您在实际代码中使用它,它将需要在其模块结束之前获取具体类型。您不能将弱类型变量保留为未定义,否则您会收到此错误:

Error: The type of this expression, '_weak1 -> '_weak1,
contains type variables that cannot be generalized

关于OCaml 坚持函数不是多态的,但不指定类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50460061/

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