OCaml Optional Argument

前端 未结 2 772
猫巷女王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:38

    OCaml has optional arguments, but it's quite a bit trickier than you would expect because OCaml functions fundamentally have exactly one argument. In your case, foo is a function that expects an int and returns a function.

    If you leave off trailing arguments, normally this means that you're interested in the function that will be returned; this is sometimes called partial application.

    The result is that trailing optional arguments (as you are asking for) do not work.

    Optional arguments are always associated with a name, which is used to tell whether the argument is being supplied or not.

    If you make z the first argument of your function rather than the last, you can get something like the following:

    # let foo ?(z = 0) x y = x + y > z;;
    val foo : ?z:int -> int -> int -> bool = 
    # foo 3 3 ~z: 2;;
    - : bool = true
    # foo 3 3 ~z: 10;;
    - : bool = false
    # foo 2 1;;
    - : bool = true
    

    In general I'd say that optional (and named) arguments in OCaml don't solve the same problems as in some other languages.

    I personally never define functions with optional arguments; so, there may be better ways to achieve what you're asking for.

提交回复
热议问题