I have defined a Matrix module as follows:
module Matrix =
struct
type 'a matrix = 'a array array
let make (nr: int) (nc: int) (init: 'a) : 'a matrix =
let result = Array.make nr (Array.make nc init) in
for i = 0 to nr - 1 do
result.(i) <- Array.make nc init
done;
result
let copy (m: 'a matrix) : 'a matrix =
let l = nbrows m in
if l = 0 then m else
let result = Array.make l m.(0) in
for i = 0 to l - 1 do
result.(i) <- Array.copy m.(i)
done;
result
...
Then I could code for instance let mat = Matrix.make 5 5 100. The advantage of defining Matrix module is to hide the type of its components. For example, I may later want to define a matrix with 'a list list or with map. I will just need to change this module, but not the code who uses this module.
But one problem I realize is that, if I do let m1 = m0 in ..., m1 and m0 will share a same physical item: any change to m1 will affect m0. Actually this is the purpose of the copy function. But is there a way to let the module always call copy for an affectation?
The worse is for a function let f (m: 'a matrix) = ..., any change inside f to m will affect the outer parameter who past its value to m. Is there a way to avoid f to do so?
When you write
let m1 = m0, the namesm1andm0denote the same object. This is not an assignment, it is a binding of a value to a name. Since the expression after the=sign is a simple name, both namesm1andm0have the same value bound to them.If you want to make a copy of a mutable data structure, you must request that copy explicitly.
If you want to be able to pass data around without having to modify it, this data must be immutable. This, indeed, is a key reason to use immutable data. When you use mutable data, you need to think carefully about sharing between data structures and who is responsible for copying when needed.
While you can reorganize any data structure to be immutable, dense matrices are not an example where immutability shines, because immutable representations of dense matrices tend to require rather more memory and more processing time.