在OCaml中的不可变记录或对象更新期间共享多少内存?

wye*_*r33 2 ocaml

在OCaml中的不可变记录或对象更新期间,对象之间共享了多少内存?例如,对于代码中的记录:

type foo = {
    a : int;
    b : int;
    c : int}

let f1 = {a = 1; b=2; c=3}
let f2 = {f1 with c=4}
Run Code Online (Sandbox Code Playgroud)

f1和之间共享多少内存f2?基本上,他们共享内存ab?同样,对于代码中的对象:

type ('i, 'j) lens = { get : 'j; set : 'j -> 'i }
class bar = object
    val a = 1
    method a = {
        get = a;
        set = fun a' -> {< a = a' >}
    }
    val b = 2
    method b = {
        get = b;
        set = fun b' -> {< b = b' >}
    }
    val c = 3
    method c = {
        get = c;
        set = fun c' -> {< c = c' >}
    }
end
let b1 = new bar
let b2 = b1#c.set 4
Run Code Online (Sandbox Code Playgroud)

b1和之间共享多少内存b2

基本上,想象的情况下的字段a,b以及c是真的,真的很大.我想做一个不可变的更新,但我不想在可能的情况下复制所有内存.

Tho*_*ash 6

对于记录,之间不会有共享内存f1,f2因为它int占用的内存与指针一样多.如果您有更复杂的对象而不是int.例如在

type foo = {
  a : int list;
  b : int list;
  c : int list;
}

let f1 = {a = [1; 1; 1]; b = [2; 2; 2]; c = [3]}
let f2 = {f1 with c = [4]}
Run Code Online (Sandbox Code Playgroud)

将在两个记录之间共享1和2的列表.

这是一个简单类型(在ocaml的一般规则int,char,bool,...)被复制,但复杂的类型('a list,'a array,...)是共享的.这就是不可变数据结构很好的原因:您可以轻松共享.但请注意,即使数据是可变的,也会共享数据:

type foo = {x : int ref; y : int ref}
let a = {x=ref 0; y = ref 0}
let b = {a with y = ref 1}
let () = b.x := 2
Run Code Online (Sandbox Code Playgroud)

然后a.x等于2.