Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/google-apps-script/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ocaml 末尾的可选参数影响前面的标签参数_Ocaml - Fatal编程技术网

Ocaml 末尾的可选参数影响前面的标签参数

Ocaml 末尾的可选参数影响前面的标签参数,ocaml,Ocaml,为什么让f~x?(y=1)=x-y是否需要参数x的标签?换句话说,当我试图计算f3~y:2,我收到此错误: Error: The function applied to this argument has type x:int -> int This argument cannot be applied without label 这种设计背后的原因是什么?没有必要给参数x加上标签: let g = f 0 工作并返回类型为?y:int->int的函数g 要理解这种行为,最好记住一般规

为什么
让f~x?(y=1)=x-y是否需要参数
x
的标签?换句话说,当我试图计算
f3~y:2,我收到此错误:

Error: The function applied to this argument has type x:int -> int
This argument cannot be applied without label

这种设计背后的原因是什么?

没有必要给参数x加上标签:

let g = f 0
工作并返回类型为
?y:int->int
的函数
g

要理解这种行为,最好记住一般规则是 应用函数时,标签是必需的

然而,总应用程序有一个特定的规则:如果一个函数应用于尽可能多的非可选参数,则可以省略标签

一个典型的例子是

let f ~a ~b c d ~e f ~g = a + b + c + d + e + f + g
let x = f 1 2 3 4 5 6 7  
回到您的情况,函数
f
最多接受一个非可选参数。因此,当仅适用于一个参数时,它被视为完全适用

另一个要点是,只有在发送了后续位置参数后,才将可选参数发送到函数。这解释了为什么变量
g
仍然是一个函数:没有向
f
提供位置参数,因此可选参数
?y
从未发送到
f

应用于更复杂的示例

let f ~a ?(b=0) c ~d e ~f ~g ?(h=0) = a + b + c + d +e + f + g + h 
 (* there are 8 arguments, 2 optional *)
 (* g is applied to the full 6 non-optional arguments, thus total *)
let g = f 1 3 4 5 6 7
g
的类型是
?h:int->0
。实际上,应用程序是完整的,因此提供了所有非可选参数。然后,第一个可选参数
?b
后面跟着一个位置参数。然后将其提供给函数。但是,最后一个可选参数
?h
尚未触发,仍在此处

此行为意味着,可选参数只有在后面至少有一个位置参数时才有用,正如编译器本身所建议的:

let f ~x ?(y=0) = x + y;;
Line 1, characters 11-14:
Warning 16: this optional argument cannot be erased.