OCaml可选参数 [英] OCaml Optional Argument

查看:98
本文介绍了OCaml可选参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在OCaml中编写一个或多个参数为可选的函数?

How can I write a function in OCaml in which one or more argument are optional?

let foo x y z = if(x+y > z) then true else false;;

如果foo没有收到 z 参数它使用 0 作为 z

If foo do not receive the z argument it uses 0 as z.

foo 3 3 2 -> true
foo 3 3 10 -> false
foo 2 1 -> true

是否有任何OCaml功能可以实现此目的?

Is there any OCaml feature to achieve this?

推荐答案

OCaml没有像在Java或C#中找到的可选参数。由于可以部分应用函数,因此可选参数可能会使您很难分辨何时传递参数,并希望函数被评估。但是,OCaml的使用默认值标记的参数,这可以用于相同的效果。

OCaml doesn't have optional arguments like you'd find in Java or C#. Since functions can be partially applied, optional arguments can make it hard to tell when you're done passing arguments and would like the function to be evaluated. However, OCaml does have labeled arguments with default values, which can be used to the same effect.

标签参数的通常注意事项适用。请注意,带标签的参数不能出现在参数列表的末尾,因为只要它具有所需的所有内容即可评估函数:

The usual caveats of labeled arguments apply. Note that labeled arguments can't appear at the end of the argument list since the function is evaluated as soon as it has everything it needs:

let foo x y ?z_name:(z=0) = (x + y) > z;;
Characters 12-39:
  let foo x y ?z_name:(z=0) = (x + y) > z;;
              ^^^^^^^^^^^^^^^^^^^^^^^^^^^
Warning 16: this optional argument cannot be erased.
val foo : int -> int -> ?z_name:int -> bool = <fun>

参数列表的其他部分很好:

Other parts of the argument list are fine:

# let foo ?z:(z=0) x y = (x + y) > z;;
val foo : ?z:int -> int -> int -> bool = <fun>
# foo 1 1;;
- : bool = true
# foo (-1) (-1);;
- : bool = false
# foo ~z:(-42) (-1) (-1);;
- : bool = true

与上面相同,您失去了提供可选参数,一旦你将它移过参数列表:

In the same fashion as above, you lose the ability to supply the optional argument once you 'move past' it in the argument list:

# foo 1;;
- : int -> bool = <fun>

这篇关于OCaml可选参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆