OCaml Optional Argument

前端 未结 2 771
猫巷女王i
猫巷女王i 2021-02-14 17:10

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;;

If foo do

2条回答
  •  耶瑟儿~
    2021-02-14 17:44

    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 = 
    

    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 = 
    # 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 = 
    

提交回复
热议问题