Strange default value behavior

I'm just starting to learn OCaml. And I have a question, why does this code display different results every time I call him?

let b () = Unix.time ();;
let a ?(c = b ()) () = c;;
a ();;
...
a ();;

I expected the default value of c to be computed once.

+4
source share
1 answer

Additional parameters are described in Section 6.7 of the OCaml manual. Here is what he says:

View function

 fun ? lab :(  pattern =  expr0 ) ->  expr

equivalently

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 not specified when calculating expr 0.

This shows what expr0is evaluated on each call if an additional parameter is not specified. Ie, expr0is inside the lambda, not the outside.

+4
source

Source: https://habr.com/ru/post/1523710/


All Articles