'Is there a way to obtain a 'reference' to a mutable struct field

So I have a record type with mutable field:

type mpoint = { mutable x:int ; mutable y: int };;
let apoint = { x=3 ; y=4};;

And I have a function that expects a 'ref' and does something to its contents. For example:

let increment x = x := !x+1;;
val increment : int ref -> unit = <fun>

Is there a way to get a 'reference' from a mutable field so that I can pass it to the function. I.e. I want to do something like:

increment apoint.x;; (* increment value of the x field 'in place' *)
Error: This expression has type int but an expression was expected of type
         int ref

But the above doesn't work because apoint.x returns the value of the field not its 'ref'. If this was golang or C++ maybe we could use the & operator to indicate we want the address instead of the value of the field: &apoint.x.

(How) can we do this in Ocaml?

PS: Yes, I know its probably more common to avoid using side-effects in this way. But I promise, I am doing this for a good reason in a context where it makes more sense than this simplified/contrived example might suggest.



Solution 1:[1]

There's no way to do exactly what you ask for. The type of a reference is very specific:

# let x = ref 3
val x : int ref = {contents = 3}

A reference is a record with one mutable field named contents. You can't really fabricate this up from an arbitrary mutable field of some other record. Even if you are willing to lie to the type system, a field of a record is not represented at all the same as a record.

You could declare your fields as actual references:

type mpoint = { x: int ref; y: int ref; }

Then there is no problem, apoint.x really is a reference. But this representation is not as efficient, i.e., it takes more memory and there are more dereferences to access the values.

If an API is designed in an imperative style it will be difficult to use in OCaml. That's how I look at it anyway. Another way to say this is that ints are small. The interface should perhaps accept an int and return a new int, rather than accepting a reference to an int and modifying it in place.

Solution 2:[2]

Jeffrey Scofield explained why this can't be done in ocaml from the point of the type system.

But you can also look at it from the point of the GC (garbage collector). In ocaml internally everything is either a trivial type (int, bool, char, ...) that is stored as a 31/63 bit value or a pointer to a block of memory. Each block of memory has a header that describes the contents to the GC and has some extra bits used by GC.

When you look at a reference internally it is a pointer to the block of memory containing the record with a mutable contents. Through that pointger the GC can access the header and know the block of memory is still reachable.

But lets just assume you could pass apoint.y to a function taking a reference. Then internally the pointer would point to the middle of apoint and the GC would fail when it tries to access the header of that block because it has no idea at what offset to the pointer the header is located.

Now how to work around this?

One way that was already mentioned is to use references instead of mutable. Another way would be to use a getter and setter:

# type 'a mut = (unit -> 'a) * ('a -> unit);;
type 'a mut = (unit -> 'a) * ('a -> unit)

# type mpoint = { mutable x:int ; mutable y: int };;
type mpoint = { mutable x : int; mutable y : int; }

# let mut_x p = (fun () -> p.x), (fun x -> p.x <- x);;
val mut_x : mpoint -> (unit -> int) * (int -> unit) = <fun>

# let mut_y p = (fun () -> p.y), (fun y -> p.y <- y);;
val mut_y : mpoint -> (unit -> int) * (int -> unit) = <fun>

If you only want to incr the variable you can pass an incrementer function instead of getter/setter. Or any other collection of helper functions. A getter/setter pait is just the most generic interface.

Solution 3:[3]

You can always copy temporarily the content of field, call the function on that, and back again:

let increment_point_x apoint =
  let x = ref apoint.x in
  increment x;
  apoint.x <- !x

Certainly not as efficient (nor elegant) as it could, but it works.

Solution 4:[4]

It is impossible to do exactly what the question asks for (@JeffreyScofield explains why, so I won't repeat that). Some workarounds have been suggested.

Here is another workaround that might work if you can change the implementation of the increment function to use a 'home made' ref type. This comes very close to what was asked for.

Instead of having it take a 'built-in' reference, we can define our own type of reference. The spirit of a 'reference' is something you can set and get. So we can characterise/represent it as a combination of a get and set function.

type 'a ref = {
  set: 'a -> unit;
  get: unit -> 'a;
};;
type 'a ref = { set : 'a -> unit; get : unit -> 'a; }

We can define the usual ! and := operators on this type:

let (!) cell = cell.get ();;
val ( ! ) : 'a ref -> 'a = <fun>

let (:=) cell = cell.set;;
val ( := ) : 'a ref -> 'a -> unit = <fun>

The increment function's code can remain the same even its type 'looks' the same (but it is subtly 'different' as it is now using our own kind of ref instead of built-in ref).

let increment cell = cell := !cell + 1;;
val increment : int ref -> unit = <fun>

When we want a reference to a field we can now make one. For example a function to make a reference to x:

let xref pt = {
  set = (fun v -> pt.x <- v);
  get = (fun () -> pt.x); 
};;
val xref : mpoint -> int ref = <fun>

And now we can call increment on the x field:

increment (xref apoint);;
- : unit = ()

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Goswin von Brederlow
Solution 3 BlackBeans
Solution 4