Version française
Home     About     Download     Resources     Contact us    
Browse thread
Re: Caml wish list
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: John Prevost <prevost@m...>
Subject: Re: reference initialization
>>>>> "hx" == Hongwei Xi <hwxi@ececs.uc.edu> writes:

    hx> I have given some thoughts on this one.

    hx> I find that it is really not a good design choice to
    hx> initialize every reference in all ML-like languages (yes, I
    hx> well realize the difficulty in not doing so). Here is my
    hx> argument.

The contrary argument is twofold.

First--if you want a reference which you may assign no initial value
to, you can use an option.  Certainly, this is yet another bit of
overhead.  (But the good thing is that unlike in Java, you have the
choice to always receive a not-null value, and therefore you don't
have to check all the time!)

Second--as for uninitialized values and loops and the like: try to
find a better way to do it.  I don't remember the last time I had to
use a reference in a loop to get what I wanted.  I hardly remember the
last time I used a reference.

Another reason to prefer this second approach (especially in a loop)
is that O'Caml's GC mechanism implies that destructive updates of heap
values are slower than variable changes, so the tail-recursive loop:

let test l =
  let rec loop n = function 
    | [] -> n
    | _ :: t -> loop (n + 1) t
  in loop 0 l

is more efficient than:

let test l =
  let l' = ref l in
  let n = ref 0 in

 let n = ref 0 in
  while !l' <> [] do
    incr n;
    l' := List.tl l'
  done;
  !n

even if you ignore the cost of repeatedly dereferencing--just because
of the cost of updating.  IMO, it's easier to read, too, though you
need to be used to the idiom.

Note that a loop like "for i = 1 to n" is as efficient (or more so,
possibly, I don't remember) as the equivalent tail recursive loop.
Why?  Because like the tail recursive call, all updates are temporary
storage in the stack, not values in the heap.


I have not seen the message you are replying to, so I don't know if it
addresses your specific concerns--but it might, I hope, clarify
something about ML style type systems that I find very important: the
ability to *choose* what features a variable has.  (Optional value,
mutable value) rather than always having to deal with optional mutable
values.

John.