I am a bit confused about the weak polymorphism in OCaml.
See the following snippet where I define the remember function:
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 used locally.
But when I change the above code to
let remember = let cache = ref None in (fun x -> match !cache with | Some y -> y | None -> cache := Some x; x) ;;
the compiler displays the weakly polymorphic type '_a -> '_a , it also seems that the cache is shared between remember calls.
Why does the compiler enclose a weakly polymorphic type here and why cache shared?
Moreover, 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 so?
functional-programming ocaml ml value-restriction
innovation_cat
source share