In PHP, default values for arguments can be set as follows:
function odp(ftw = "OMG!!") {
//...
}
Is there similar functionality in OCaml?
Once a default value is used for an argument in the function definition, all subsequent arguments to it must have a default value as well. It can also be stated that the default arguments are assigned from right to left.
The way -> is defined, a function always takes one argument and returns only one element. A function with multiple parameters can be translated into a sequence of unary functions.
The tilde introduces the feature known as labelled argument. OCaml standard library has module List where functions are declared without labelled arguments and module ListLabels which uses them.
We've seen how to assign functions to variables. Now let's take a look at how we might utilize the fact that functions are first class functions in OCaml. The kind community at Stack Overflow has generated a list of examples in other languages.
OCaml doesn't have optional positional parameters, because, since OCaml supports currying, if you leave out some arguments it just looks like a partial application. However, for named parameters, there are optional named parameters.
Normal named parameters are declared like this:
let foo ~arg1 = arg1 + 5;;
Optional named parameters are declared like this:
let odp ?(ftw = "OMG!!") () = print_endline ftw;;
(* and can be used like this *)
odp ~ftw:"hi mom" ();;
odp ();;
Note that any optional named parameters must be followed by at least one non-optional parameter, because otherwise e.g "odp" above would just look like a partial application.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With