Jackson Tale
Jackson Tale

Reputation: 25812

Is it possible to write a weakly polymorphism function without involving ref or partial application?

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?

Upvotes: 0

Views: 80

Answers (2)

gsg
gsg

Reputation: 9377

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.

Upvotes: 4

ivg
ivg

Reputation: 35210

It is possible with other mutable data structures, like array, bigarray, objects, and other structures, that have construction of the form create: unit -> 'a t, or create: some_type -> 'a t, so that they can be created without actually proving to a compiler, that they will have a specified type.

Upvotes: 1

Related Questions