作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
考虑这个代码:
let myFun
?(f: ('a -> int) = (fun x -> x))
(x: 'a)
: int =
f x
int
以外的其他参数调用。当我尝试使用此代码时:
let usage = myFun ~f:String.length "abcdef"
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
应该具有不同类型以获得所需功能的事实。
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。
optional
类型。然而,这很容易导致严重的类型错误,并且相应的复杂性增加不会成为非常有吸引力的扩展。
关于ocaml - 过于急切地推断 ocaml 可选函数参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43918511/
我正在尝试用 Swift 编写这段 JavaScript 代码:k_combinations 到目前为止,我在 Swift 中有这个: import Foundation import Cocoa e
我是一名优秀的程序员,十分优秀!