let remember =
let cache = ref None in
(fun x -> match !cache with
| Some y -> y
| None -> cache := Some x; x)
是弱多态性,但涉及ref
.
有什么方法可以在不涉及ref
or的情况下编写弱多态函数partial application
?
let remember =
let cache = ref None in
(fun x -> match !cache with
| Some y -> y
| None -> cache := Some x; x)
是弱多态性,但涉及ref
.
有什么方法可以在不涉及ref
or的情况下编写弱多态函数partial application
?
当然。模块抽象会做到这一点,本质上是指示编译器放弃有关实现的所有信息:
module Example : sig
type 'a t
val create : unit -> 'a t
end = struct
type 'a t = int
let create () = 0
end
和弱多态结果:
# let x = Example.create ();;
val x : '_a Example.t = <abstr>
(请注意,如果您想要在这里实现多态性,您将使用方差注释来恢复它。)
基于(数组,可变字段)以外的可变结构构建示例也很容易ref
,但这并不是很有指导意义,因为它几乎是一回事。
可以使用其他可变数据结构,如数组、大数组、对象和其他结构,它们具有create: unit -> 'a t
或形式的构造create: some_type -> 'a t
,因此可以在不向编译器实际证明它们将具有指定类型的情况下创建它们。