let remember =
let cache = ref None in
(fun x -> match !cache with
| Some y -> y
| None -> cache := Some x; x)
is weakly polymorphism, but involving ref
.
Any ways to write a weakly polymorphism function without involving ref
or partial application
?
Sure. Module abstraction will do it, essentially instructing the compiler to abandon all information about the implementation:
module Example : sig
type 'a t
val create : unit -> 'a t
end = struct
type 'a t = int
let create () = 0
end
and the weakly polymorphic result:
# let x = Example.create ();;
val x : '_a Example.t = <abstr>
(Note that if you wanted polymorphism here, you would use variance annotations to recover it.)
It's also easy to construct examples based on mutable structures other than ref
(arrays, mutable fields), but that's not very instructive as it is pretty much the same thing.