Reputation: 2232
I just start learning OCaml. And I have a question, why this code outputs different results every time I call him?
let b () = Unix.time ();;
let a ?(c = b ()) () = c;;
a ();;
...
a ();;
I expected, that default value of c will be compute once.
Upvotes: 4
Views: 65
Reputation: 66803
Optional parameters are described in Section 6.7 of the OCaml manual. Here's what it says:
A function of the form
fun ? lab :( pattern = expr0 ) -> expr
is equivalent to
fun ? lab : ident ->
let pattern = match ident with
| Some ident -> ident
| None -> expr0
in
expr
where ident is a fresh variable, except that it is unspecified when expr0 is evaluated.
This shows expr0
being evaluated at each call, if the optional parameter is not supplied. I.e., expr0
is inside the lambda, not outside.
Upvotes: 4