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
How to do this properly with OCaml?
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: 2005-07-26 (00:46)
From: Brian Hurt <bhurt@s...>
Subject: Re: [Caml-list] How to do this properly with OCaml?

On Mon, 25 Jul 2005, skaller wrote:

> On Sun, 2005-07-24 at 23:45 -0700, Stephane Glondu wrote:
>> It would surely be interesting. But now, we have moved from "using
>> Obj.magic for better efficiency" to "modifying to collector"...
> Well, basically the real topic is how to implement variable
> length arrays. This is easy enough in C and C++: why should
> it be very hard or even impossible in Ocaml?

It is, in fact, neither- *IF* you don't mind a little bit of inefficiency.

For example:

type 'a t = {
     mutable len: int;
     mutable data: 'a option array;

let make init_size =
     let init_size = if init_size <= 0 then 16 else init_size in
     { len = 0; data = Array.make init_size None }

let get arr idx =
     if (idx < 0) || (idx > arr.len) then
        invalid_arg "get_arr"

let append arr x = (* add x to the end of arr *)
     if (arr.len == (Array.length arr.data)) then
             let newarr = Array.make (2*arr.len) None in
             Array.blit arr.data 0 newarr 0 arr.len;
             arr.data <- newarr;
     arr.data.(arr.len) <- Some(x);
     arr.len <- arr.len + 1;

It's insisting that it be done without options that's tricky.

As a side note, whenever I or anyone else starts bitching about how 
something is easy to do in C but hard to do in Ocaml, that's a sign that 
I'm approaching the problem wrong.  Most likely, you need some sort of 
deque or other data structure.

> The language requirements with respect to initialisation
> are the difference: Ocaml requires all store to be
> initialised, C/C++ does not.

Yep.  The following C code is really hard to implement in Ocaml:
     char * ptr = (char *) 0xA00000ul;
     ptr[315] = 'a';

I consider this an advantage of Ocaml over C/C++.