Re: Optional arguments in functions???

"Gabriel Scherer [email protected] [ocaml_beginners]" <[email protected]> Wed, 6 Apr 2016 17:17:40 -0400
Newsgroups gmane.comp.lang.ocaml.beginners
Message-ID <CAPFanBF5V-X+u-OrhVvu9xZ=nD0O5G-5_PZGeHJTZrD1YFwFuQ@mail.gmail.com>
The syntax is ?(z=1), not ?z(z=1).
Another problem is that an optional argument cannot be the last argument of
the function (because the typer uses the application of the *following*
argument to know that you indeed omit the optional argument instead of only
doing partial application), so you should actually write something like
  let multiply ?(z=1) x y = x*y*z;;

You won't be able to write
  multiply 1 2 3
though, you need to explicitly pass the argument,
  multiply 1 2 ~z:3

See the OCaml manual, Section 4.1.1, Optional arguments:
  http://caml.inria.fr/pub/docs/manual-ocaml/lablexamples.html#sec43

On Wed, Apr 6, 2016 at 5:00 PM, Douglas Lewit [email protected]
[ocaml_beginners] <[email protected]> wrote:

>
>
> Hi everyone,
>
> I'm experiencing some issues with optional arguments passed to functions
> in Ocaml.  For example, let's say I want to write a function like this:
>
> let multiply x y ?z(z = 1) = x * y * z ;;
>
> This doesn't work in utop.  What I'm trying to do is this.  If two
> arguments are passed to the function, then just return the product of those
> two arguments.  ( Because x * y * 1 is always the same as x * y. )  But if
> three arguments are passed, then return the product of all three integers.
> What am I doing wrong?  There must be a way to do this.  Thanks for sharing!
>
> Best,
>
> Douglas.
>
>
>
> 
>