Version française
Home     About     Download     Resources     Contact us    
Browse thread
Avoiding shared data
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: Bill Wood <william.wood3@c...>
Subject: Re: [Caml-list] Avoiding shared data
   . . .
> I need to process arrays of pairs of integers and
> records ((int * record) array) in which all elements
> must be updated individually, which means that
> unshared data structures must be used. For arrays of
> arrays I can produce unshared data by using the
> library functions Array.copy and Array.append to
> append the individual arrays into the embedding array.
> It works, the low level arrays can be updated
> individually. But I cannot use the same scheme to the
> array of the (int * record) structures, because I do
> not know how to copy these structures to dissolve the
> sharing. I do not even know how to copy records. It
> seems to me that this problem occurs always when I
> want to produce an array of data with a fixed
> structure automatically (rather than entering the
> array [| ... |] by hand at the top level interpreter
> using constants only). How can I produce completely
> unshared structures?

Funny you should mention it, I wrestled with this just this week.  I'm
building a square, i.e. array of N elements, each of which is itself an
array of N cells, where a cell is a record with several fields.  Here's
the way I did it:

1) I defined a function initial_cell : unit -> cell as

   let initial_cell () =
     let c = {field1 = val1; ...; fieldN = valN} in
       c;;

2) I defined a function initial_row : int -> cell array as:

   let initial_row n = Array.init n (fun i -> initial_cell ());;

3) I defined a function initial_square : int -> cell array array by:

   let initial_square n = Array.init n (fun i -> initial_row ());;

I think the essential point is the Array.init function; since it expects
to set the i-th element of the new array to (f i) for unknown f, it
can't make an array that shares.

I hope this is of some help,

 -- Bill Wood
    bill.wood@acm.org