I am a little confused about weak polymorphism in OCaml.
Please see the following snippet, where I define a function remember
:
let remember x =
let cache = ref None in
match !cache with
| Some y -> y
| None -> cache := Some x; x
;;
The compiler can infer the polymorphic type 'a -> 'a
, and cache
is used locally.
But when I modify the above code into
let remember =
let cache = ref None in
(fun x -> match !cache with
| Some y -> y
| None -> cache := Some x; x)
;;
the compiler infers the weakly polymorphic type '_a -> '_a
, also, it seems that cache
is shared across invocations of remember
.
Why does the compiler infer a weakly polymorphic type here and why is cache
shared?
What is more, if I change the code again
let remember x =
let cache = ref None in
(fun z -> match !cache with
| Some y -> z
| None -> cache := Some x; x)
;;
the compiler infers the polymorphic type 'a -> 'a -> 'a
and cache
becomes locally used. Why is this the case?
cache
has typeint option ref
and notref (None int)
. – Battlefield