Re: Question regarding the creation of arrays
| Newsgroups | gmane.comp.lang.ocaml.beginners |
|---|---|
| Message-ID | <CAPFanBF7LEZVUP8d8L3Uj0k_66ddP39AodY4o_PDmcq6Eti=kg@mail.gmail.com> |
You can define make_matrix yourself as:
let make_matrix m n v =
Array.init m (fun _ -> Array.init n v)
this technique can easily be extended to arbitrary dimensions, for example:
Array.init n1 (fun _ ->
Array.init n2 (fun _ ->
Array.make n v))
Note that (Array.make m (Array.make n v)) would be terribly wrong
because of aliasing: the sub-arrays of the larger array are the same,
and get modified at the same time:
# let t = Array.make 2 (Array.make 2 0);;
val t : int array array = [|[|0; 0|]; [|0; 0|]|]
# t.(0).(1) <- 1; t;;
- : int array array = [|[|0; 1|]; [|0; 1|]|]
This is why Array.init, which recompute a fresh sub-array for each
index, should be used instead.
On Tue, Jul 22, 2014 at 6:10 AM, Nicolas FRANCOIS
[email protected] [ocaml_beginners]
<[email protected]> wrote:
> Hi.
>
> To create a fresh one dimmension array, we use Array.create. For 2
> dimensions, we can use Array.make_matrix.
>
> What is the general construction for a 3 or more dimensions array ?
>
> Thanks for your answers.
>
> \bye
>
> --
>
> Nicolas FRANCOIS | /\
> http://nicolas.francois.free.fr | |__|
> X--/\\
> We are the Micro$oft. _\_V
> Resistance is futile.
> You will be assimilated. darthvader penguin
>
>
> ------------------------------------
> Posted by: Nicolas FRANCOIS <[email protected]>
> ------------------------------------
>
> Archives up to December 31, 2011 are also downloadable at http://www.connettivo.net/cntprojects/ocaml_beginners
> The archives of the very official ocaml list (the seniors' one) can be found at http://caml.inria.fr
> Attachments are banned and you're asked to be polite, avoid flames etc.
> ------------------------------------
>
> Yahoo Groups Links
>
>
>