views:

228

answers:

1

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

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

Is there similar functionality in OCaml?

+5  A: 

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.

newacct
typically, I would just use "let foo arg1 = arg1 + 5;;", without the "~". What is the point of that?
Rosarch
you can read about them here: http://caml.inria.fr/pub/docs/manual-ocaml/manual006.html#htoc37
newacct