Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OCaml: Default values for function arguments?

In PHP, default values for arguments can be set as follows:

function odp(ftw = "OMG!!") {
   //...
}

Is there similar functionality in OCaml?

like image 973
Nick Heiner Avatar asked Sep 15 '09 03:09

Nick Heiner


People also ask

Can a function argument have default value?

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.

What does -> mean in OCaml?

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.

What does tilde mean in OCaml?

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.

Are functions first class in OCaml?

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.


1 Answers

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.

like image 135
newacct Avatar answered Oct 05 '22 09:10

newacct