【发布时间】:2014-12-04 09:54:29
【问题描述】:
我可以理解allowing mutable是值限制和弱多态的原因。基本上,函数内部的可变 ref 可能会改变所涉及的类型并影响函数的未来使用。所以在类型不匹配的情况下可能不会引入真正的多态性。
例如,
# let remember =
let cache = ref None in
(fun x ->
match !cache with
| Some y -> y
| None -> cache := Some x; x)
;;
val remember : '_a -> '_a = <fun>
请记住,缓存最初是'a option,但是一旦第一次调用let () = remember 1,缓存就会变成int option,因此类型变得有限。值限制解决了这个潜在的问题。
我仍然不明白的是部分应用的价值限制。
例如,
let identity x = x
val identity: 'a -> 'a = <fun>
let map_rep = List.map identity
val map_rep: '_a list -> '_a list = <fun>
在上面的函数中,我没有看到任何 ref 或可变的地方,为什么仍然应用值限制?
【问题讨论】:
标签: ocaml