OCaml Array Confusion

I’m a little confused by what an array is in OCaml. I know an array is mutable but how is that accomplished? I also know you can’t get a reference to an array element, only its value. I know I can create an array of references and the get that reference because that’s the value.

I’m a little confused as to what an array is… Is it just a reference to a block of memory that you can index into? Why can’t you get a reference to a position in a OCaml array?

The section of the OCaml manual gives details about OCaml blocks: https://caml.inria.fr/pub/docs/manual-ocaml/intfc.html#s:c-value

An array is the address of a block, and this is not just the address of the first cell of data but also where the length of the block and the kind of block (tag) is stored. The length and tag are needed for a few things, one of them being bound checking. That’s why OCaml doesn’t offer the notion of reference or pointer to some position in an array. For the correct details, see the link above. :slight_smile:

1 Like

Indeed, for the runtime itself, just about everything looks like an array. You can - for the purposes of playing with the runtime only - see it, for example making a 3-tuple behave like a 3-element non-uniform array:

# let foo = (42, "42", 42.);;
val foo : int * string * float = (42, "42", 42.)
# (Obj.magic foo).(0) <- 0;;
- : unit = ()
# (Obj.magic foo).(1) <- "0";;
- : unit = ()
# foo;;
- : int * string * float = (0, "0", 42.)

[but note that you should never do this in actual code! For example, if you try (Obj.magic foo).(2) <- 0. you will instantly segfault the runtime if you try to display foo again, unless you’re using a runtime built without flat float arrays, and furthermore breaking the type system’s tracking of mutability like this can result in incorrect code being generated by ocamlopt]

3 Likes