Browse thread
[Caml-list] help
[
Home
]
[ Index:
by date
|
by threads
]
[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
| Date: | -- (:) |
| From: | Brian Hurt <bhurt@s...> |
| Subject: | [Caml-list] Re: help |
On Sun, 25 Apr 2004, mohammad siddiqui wrote:
> Hello,
>
> I am having problem dealing with data structures in OCAML, I am translating
> code from C to OCAML. As shown below one structure contains array of other
> structures as its field. One of the guys here told me that we cant inline
> structures into other structures in OCAML.
That was me.
Let's consider the C code:
typedef struct {
int a;
int b;
} foo_t;
typedef struct {
int c;
foo_t * arr;
} bar_t;
void f(bar_t * ptr) {
/* Change a foo_t */
ptr->arr[ptr->c].a += 1;
ptr->arr[ptr->c].b -= 1;
}
Fairly simply, and basically what you want to do, right? Now, Ocaml can't
"inline" (unbox is what I should have said) the foo_t's into the array.
So you can't do the above code. What you *can* implement code like (C
again):
typedef struct {
int c;
foo_t ** arr;
} bar_t;
void f(bar_t ptr) {
ptr->arr[ptr->c]->a += 1;
ptr->arr[ptr->c]->b -= 1;
}
Notice the extra level of indirection- arr is no longer a pointer to an
array of foo_t's, but instead a pointer to an array of pointers to
foo_t's.
Now, the precise translation of this, second version of the code, is this:
type foo_t = { mutable a: int; mutable b: int };;
type bar_t = { c: int; arr: foo_t array };;
let f ptr =
ptr.arr.(ptr.c).a <- ptr.arr.(ptr.c).a + 1;
ptr.arr.(ptr.c).b <- ptr.arr.(ptr.c).b - 1
;;
But we can do better than this, by converting the structures to tuples,
giving us:
type foo_t = int * int;;
type bar_t = int * (foo_t array);;
let f ((c, arr) : bar_t) =
arr.(c) <-
begin
match (arr.(c)) with
| (a, b) -> (a+1, b-1)
end
;;
Here we're taking advantage of the fact that the foo_t's are boxed (not
inlined), by simply throwing the old tuple out and replacing it with a new
tuple with the correct new values.
Does this help?
--
"Usenet is like a herd of performing elephants with diarrhea -- massive,
difficult to redirect, awe-inspiring, entertaining, and a source of
mind-boggling amounts of excrement when you least expect it."
- Gene Spafford
Brian
-------------------
To unsubscribe, mail caml-list-request@inria.fr Archives: http://caml.inria.fr
Bug reports: http://caml.inria.fr/bin/caml-bugs FAQ: http://caml.inria.fr/FAQ/
Beginner's list: http://groups.yahoo.com/group/ocaml_beginners