gpt4 book ai didi

ocaml - 过于急切地推断 ocaml 可选函数参数

转载 作者:行者123 更新时间:2023-12-01 07:52:13 26 4
gpt4 key购买 nike

考虑这个代码:

let myFun
?(f: ('a -> int) = (fun x -> x))
(x: 'a)
: int =
f x

看起来我不能用 int 以外的其他参数调用。当我尝试使用此代码时:
let usage = myFun ~f:String.length "abcdef"

Ocaml 发出此错误消息:
Error: This expression has type string -> int
but an expression was expected of type int -> int
Type string is not compatible with type int

由于默认参数,看起来推理会认为 'a = int 。这是语言的限制还是有什么方法可以编写它以便编译?

最佳答案

由于 optionals 参数的实现方式,此问题是一个限制。

本质上,在类型检查阶段使用标准选项类型扩展带有可选参数的函数。例如,您的功能:

let f ?(conv=(fun x -> x)) x = f x

或多或少变成
let f opt_conv =
let conv =
match opt_conv with
| None -> fun x -> x
| Some f -> f in
fun x -> conv x

因此,由于 opt_conv'a->'a 分支中具有类型 None ,因此 f 必须具有类型 ?conv:('a->'a) -> 'a -> 'a

查看扩展函数,问题来自于 Some 分支和 None 应该具有不同类型以获得所需功能的事实。

为了类型谜语,在模式匹配的不同分支中具有不同的类型是 GADT 可能带来潜在解决方案的标志:可以将扩展选项类型定义为
type ('default,'generic) optional =
| Default: ('default,'default) optional
| Custom: 'a -> ('default,'a) optional

那么可以将您的函数重写为
let f: type a. (int -> int, a -> int) optional -> a -> int =
fun conv x ->
match conv with
| Default -> x
| Custom f -> f x

这导致了预期的行为:
f Default "hi" 产生类型错误,而 f (Custom int_of_string) "2" 返回 2。

但是,如果没有可选参数语法糖机制,这并不是真正有用的。

没有一个完全有可能扩展 OCaml 以使用 GADT 加载的 optional 类型。然而,这很容易导致严重的类型错误,并且相应的复杂性增加不会成为非常有吸引力的扩展。

关于ocaml - 过于急切地推断 ocaml 可选函数参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43918511/

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