Reputation: 1156
From what I've observed so far, records with mutable fields behave as if they are always passed by reference. E.g., if I pass a record to a function or store it in a data structure, the record does not get copied in the process. For example, this code:
type t = {
mutable t_val: int
}
let () =
let ht = Hashtbl.create 16 in
let x = { t_val = 42 } in
Hashtbl.replace ht "x" x;
x.t_val <- 43;
let x2 = Hashtbl.find ht "x" in
Format.printf "x.t_val: %d, x2.t_val: %d@." x.t_val x2.t_val
outputs
x.t_val: 43, x2.t_val: 43
Is this a reliable and intended behaviour or depends on the circumstances?
Upvotes: 2
Views: 575
Reputation: 122439
This has nothing to do with pass-by-value or pass-by-reference. For example, Java has only pass-by-value and when you pass a reference, inside the function they can also modify the fields of the object pointed to by the reference and these changes are visible to anyone else who has a reference to the same object.
(The difference between pass-by-value and pass-by-reference is in what happens when you directly assign to a parameter variable (not access the object pointed to it or anything else) inside the function; in pass-by-value, it has no effect on the passed variable in the calling scope; in pass-by-reference, it has the same effect as an assignment to the passed variable in the calling scope. In OCaml, it's not possible to directly assign to a variable after its initialization (there is simply no syntax for doing this), and therefore, there is no difference between pass-by-value and pass-by-reference.)
What you are talking about is that record types are reference types, i.e. a value of record type is actually a reference to an underlying structure, and multiple references can point to the same underlying structure, and modifications through one reference can be seen through other references to the same underlying structure. This is true. And as @kne mentioned, the only types in OCaml that are not "boxed", i.e. reference types, are simple immutable types like int
or things that can fit into an int
, and since they are immutable it mostly makes no difference whether they are reference types or value types (except perhaps for the semantics of things like ==
).
Upvotes: 1
Reputation: 1418
Yes, it is reliable and intended. In fact, not only mutable records are 'passed by reference', everything is. Only with immutable data you will never notice the difference. (There is an exception: small immutable data like int
are optimized to be handled in a pass-by-value fashion. But still, semantically you can safely assume that everything works as if it was consistently pass-by-reference.)
Upvotes: 3