如何强制OCaml推断更通用的类型? [英] how to force OCaml to infer a more general type?
问题描述
我想定义一个函数,该函数接受一个可选参数,该参数是一个函数('a->'b).默认值应该是标识,实际上是('a -> 'a)
,但是我看不出为什么它不应该与更通用的('a -> 'b)
兼容.当我尝试时:
I want to define a function that accepts an optional argument which is a function ('a -> 'b). The default value should be the identity, which is actually ('a -> 'a)
, but i see no reason why it should not be compatible with the more general ('a -> 'b)
. When i try:
let optional_apply ?f i =
match f with
| None -> i + 4
| Some fn -> fn (i + 4)
我总是得到窄型?f:(int -> int) -> int -> int
.但我想将f保留为int -> 'b
.我能做些什么?还是因为optional_apply
没有确定的类型,这才是不合理的?如果是这样,我将如何获得类似的功能?
I always get the narrow type ?f:(int -> int) -> int -> int
. But I want to keep f as int -> 'b
. What can i do? Or is this just unsound, since optional_apply
would not have a definite type? If so, how would I get a similar functionality?
推荐答案
不可能,f
参数不能为可选.一个简单的解释是,可选参数只是语法糖.
因此,不用加糖,您的函数可以按以下形式重写:
It is impossible, the f
argument must not be optional. A simple explanation, is that optional parameters are just a syntactic sugar.
So without sugar your function can be rewritten in a following form:
let optional_apply f n = match f with
| Some f -> f (n + 4)
| None -> (n + 4)
在这里,类型检查器仅允许我们为f
使用一种类型:int -> int
.如果它允许我们使用int -> 'a
类型,则表达式的None
路径将不正确.换句话说,根据f
是None
还是Some
,optional_apply
将得出不同的类型.这被认为是不健全的.
And here typechecker allows us only one type for f
: int -> int
. If it allowed us an int -> 'a
type, then the None
path of expression would be unsound. In other words, depending on whether f
is None
or Some
the optional_apply
will evaluate to different types. And this is considered unsound.
证明不健全的最好方法是举一个简单的例子,其中typechecker将允许不健全的程序:
The best way to prove the unsoundness is to give a simple example where typechecker will allow unsound program:
let f = ref None
let g n = optional_apply ?f:!f n
使用此定义,如果类型检查器允许f
参数保持多态,那么我们可以随时通过将f
引用更改为任何其他内容来破坏" g
功能.
with this definitions, if type checker allowed f
parameter to remain polymorphic, then we can at any time "break" g
function by changing f
reference to anything else.
这篇关于如何强制OCaml推断更通用的类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!