OCaml NOT safe-for-space
Henry Cejtin
henry@sourcelight.com
Wed, 10 Jan 2001 23:25:38 -0600
Did you see this on comp.lang.functional? Clearly OCaml is not quite safe-
for-space. Pretty bad when the source of the library stuff has to work around
this.
>Path: news.sinica!ctu-peer!ctu-gate!news.nctu.edu.tw!newsfeed.berkeley.edu!ucberkeley!newsfeed.mathworks.com!news.voicenet.com!nntp.upenn.edu!not-for-mail
>From: Jerome Vouillon <vouillon@saul.cis.upenn.edu>
>Newsgroups: comp.lang.functional
>Subject: Re: OCaml: live variables?
>Date: 10 Jan 2001 19:20:38 -0500
>Organization: INRIA
>Lines: 46
>Message-ID: <d3zvgrnym5l.fsf@saul.cis.upenn.edu>
>References: <93gqvh$67$1@nnrp1.deja.com>
>NNTP-Posting-Host: saul.cis.upenn.edu
>X-Newsreader: Gnus v5.5/Emacs 20.2
>Xref: news.sinica comp.lang.functional:11691
>
>xena_314159@my-deja.com writes:
>
>> I have been looking at the sources for unison as part of my OCaml
>> immersion, where I found this:
>>
>> let rec fold_left f accu l =
>> match l with
>> [] -> accu
>> | a::_ ->
>> (* We don't want l to be live when f is called *)
>> let l' = match l with _::l' -> l' | _ -> assert false in
>> fold_left f (f accu a) l'
>>
>> I have to confess, I am baffled by the comment and the intent. What
>> "liveness" issue is there here, and how does the second match expression
>> address it? Why would you prefer the above to:
>>
>> let rec fold_left f q = function
>> | [] -> q
>> | x :: xx -> foldl f (f q x) xx
>>
>> I'm concerned that there is some issue here that I am not
>> understanding.
>
>The native code compiler compiles the second function as:
>
> let rec fold_left f q = function
> | [] -> q
> | l ->
> let x = List.hd l in
> let r = f q x in
> let xx = List.tl l in
> foldl f r xx
>
>When the function f is invoked, the list l is still required in order
>to compute xx (it is still "live"). As a consequence, its head x will
>not be disallocated by the garbage collector before the function f
>returns.
>
>In the first function, the tail of the list is computed before the
>function f is invoked, so x can be freed during the invocation of f if
>it is not used anymore. Usually, this is not important, but if x is
>very large, using the first function instead of the second can lower
>the memory usage of the program significantly.
>
>-- Jerome