OCaml中高阶函数和带标签的参数的行为解释 [英] behavior explanation for higher order functions and labeled argument in OCaml
问题描述
以来自RWOCaml的示例为例:
Taking an exemple derived from RWOCaml :
utop # let divide ~first ~second = first / second;;
val divide : first:int -> second:int -> int = <fun>
utop # let apply_to_tuple_3 f (first,second) = f second first;;
val apply_to_tuple_3 : ('a -> 'b -> 'c) -> 'b * 'a -> 'c = <fun>
utop # apply_to_tuple_3 divide;;
Error: This expression has type first:int -> second:int -> int
but an expression was expected of type 'a -> 'b -> 'c
不匹配这里的类型有意义吗?
apply_to_tuple_3
仅使用了divide
当然拥有的位置参数.
Does it make sense to not match the types here ?
apply_to_tuple_3
only makes use of the positional arguments, which certainly divide
possesses.
删除姓名后,申请被接受
Upon removing the names, the application is accepted
utop # let divide_an x y = divide x y;;
val divide_an : int -> int -> int = <fun>
utop # apply_to_tuple_3 divide_an;;
- : int * int -> int = <fun>
有什么理由拒绝第一个电话吗?
Is there any reason to reject the first call ?
推荐答案
带有标签参数的函数的类型取决于标签及其显示顺序.调用此类函数时,您提供的参数顺序具有灵活性.实际上,如果提供所有参数,则可以省略标签.
Functions with labeled parameters have a type that depends on the labels and on the order that they appear. When calling such functions, there is flexibility in the order of arguments that you supply. And in fact you can omit the labels if you supply all of the arguments.
但是,当传递诸如值本身之类的函数时,则没有这种灵活性.您只有一种带有标签的类型可以使用.
However, when passing such functions as values themselves, there is no such flexibility. You have only the one labeled type to work with.
这在Real World OCaml的第42页中进行了介绍:高阶功能和标签.
This is covered on page 42 of Real World OCaml: Higher-order functions and labels.
(如果您问的是为什么,我只能假设如果允许这种灵活性,类型检查就变得困难或不可能.)
(If you're asking why this is the case, I can only assume that type checking becomes difficult or impossible if you allow such flexibility.)
这篇关于OCaml中高阶函数和带标签的参数的行为解释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!