问题描述
我正在试验Core的List.fold_left
.
I am experimenting with Core's List.fold_left
.
# List.fold_left;;
- : 'a Core.Std.List.t -> init:'b -> f:('b -> 'a -> 'b) -> 'b = <fun>
当我指定标签时,效果很好:
It works fine when I specify the labels:
# List.fold_left [1;2;3] ~init:0 ~f:(+);;
- : int = 6
但是当我不指定标签时,我得到了不同的结果:
But I get a different result when I do not specify the labels:
# List.fold_left [1;2;3] 0 (+);;
- : init:(int -> (int -> int -> int) -> '_a) ->
f:((int -> (int -> int -> int) -> '_a) ->
int -> int -> (int -> int -> int) -> '_a) ->
'_a
= <fun>
和其他部分应用程序也产生非直观类型.为什么我可以在list参数后面添加任意数量的0?
And other partial applications also yield nonintuitive types. Why can I add an arbitrary amount of 0's after the list argument?
# List.fold_left [1;2;3] 0;;
- : init:(int -> '_a) -> f:((int -> '_a) -> int -> int -> '_a) -> '_a = <fun>
# List.fold_left [1;2;3] 0 0;;
- : init:(int -> int -> '_a) ->
f:((int -> int -> '_a) -> int -> int -> int -> '_a) -> '_a
= <fun>
某些其他功能表现出相同的行为:
Some other functions exhibit the same behavior:
# let app ~f ~x = f x;;
val app : f:('a -> 'b) -> x:'a -> 'b = <fun>
# app (fun x -> x + 1) 1;;
- : f:('a -> (int -> int) -> int -> 'b) -> x:'a -> 'b = <fun>
但是,某些带标签的函数在不带标签的情况下应用时可以返回预期的结果.例如:
But some labeled functions are able to return the expected result when applied without labels given. For example:
# List.map;;
- : 'a Core.Std.List.t -> f:('a -> 'b) -> 'b Core.Std.List.t = <fun>
# List.map [1;2;3] (fun x -> x + 1);;
- : int Core.Std.List.t = [2; 3; 4]
为什么某些函数在未指定标签的情况下应用时会返回非直观值,而另一些函数却按预期工作呢?
Why does some functions return nonintuitive values when applied without labels given, while the others work as expected?
推荐答案
根据手册,您仅可以省略标签如果一个应用程序是总计的(省略所有可选参数)"和一个重要的警告,其结果类型为类型变量的ListLabels.fold_left
之类的函数将永远不会被认为完全适用."
According to the manual you may only omit labels "if an application is total (omitting all optional arguments)" with the important caveat "that functions like ListLabels.fold_left
whose result type is a type variable will never be considered as totally applied."
因此,由于core的fold_left
的结果类型当然也是类型变量,因此没有标签就无法调用它.当您执行此操作时,将发生的情况是位置参数被解释为fold_left
生成的函数的参数,并且仍在等待您提供带标签的参数.
So since core's fold_left
's result type is, of course, also a type variable, you can not call it without labels. What happens when you do is that the positional arguments are interpreted as arguments to the function produced by fold_left
and it still waits for you to provide the labeled arguments.
这篇关于使用不带标签的Core.Std.List.fold_left的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!