14

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

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

Is there similar functionality in OCaml?

Nick Heiner
  • 119,074
  • 188
  • 476
  • 699

1 Answers1

34

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
  • 119,665
  • 29
  • 163
  • 224