English version
Accueil     À propos     Téléchargement     Ressources     Contactez-nous    

Ce site est rarement mis à jour. Pour les informations les plus récentes, rendez-vous sur le nouveau site OCaml à l'adresse ocaml.org.

Browse thread
RE: reference initialization
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: 2000-05-15 (21:02)
From: Hongwei Xi <hwxi@E...>
Subject: Re: reference initialization
What I had in mind is actually something pretty simple (since it won't
be very useful if it is not simple :-))

> My gut feeling about this approach is that the type system could
> probably work well for arrays that are initialized linearly, e.g.
>         let a = Array.create n in
>         for i = 0 to n - 1 do
>           a.(i) <- ...
>           (* at this point, the type system knows that 
>              a.(0)...a.(i-1) are initialized and
>              a.(i)...a.(n-1) are not *)
>         done
>         (* at this point, the type system knowns that all elements of a
>            are initialized *)
> But notice that most of these cases are easily expressed using Array.init!

But one common case is not covered: when you initialize A[i], you may
need values stored in A[j] for some 0 <= j < i. Is it possible to make
'init' handle this case as well. I must say that I have problems writing
such a function. This is certainly a problem that people who are
interested in generic programming should study (if it has not be
studied yet).

> However, the type system is going to break horribly on more complex
> initialization patterns, e.g. the following code for tabulating the
> inverse of a permutation f over [0...n-1] :
>         let a = Array.create n in
>         for i = 0 to n - 1 do a.(f(i)) <- i done
> So, I don't think the (Caml) programmer will gain much from a type
> system/static analysis for array initialization.  (For a lower-level
> language such as TAL, the story may be different, though.)

In this case, I could imagine that there are programmers who 
would like to verify that this code indeed initialize every
array cell; this is clearly a case where initialization upon
allocation doesn't make much sense.

Is it possible to have something like the following in the library:

Array.init': int -> (int -> (int * 'a)) -> 'a Array

let Array.init' n f =
  let a = Array.create n in
  for i = 0 to n - 1 do
    let (j, v) = f i
    in a.(j) <- v
  (* then check that all cells are initilized *)