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-22 (18:59)
From: Stephane Glondu <Stephane.Glondu@c...>
Subject: Re: [Caml-list] How to do this properly with OCaml?

Christophe Dehlinger wrote:
> I have my own array-related problem, so I'll plug it here :)
> A couple of times, I would have liked to build arrays of functions whose
> body uses the array itself, like:
> #let rec foo = Array.init 5 (fun n () -> if n=0 then 0 else foo.(n/2) ())
> This kind of expression is not allowed as right-hand side of `let rec'
> Why is this kind of construct forbidden ?

In general, you cannot define a recursive value as a result of a
computation which uses the being-defined value. Intuitively, I explain
it in that way: here, the second argument references sth which is
created by Array.init itself, so the compiler has to know the result of
the call before compiling the argument function, which is clearly

You have to do sth like this:

let foo =
  let bar = Array.make 5 (fun () -> 0) in
  for n = 1 to 4 do
    bar.(n) <- (fun () -> bar.(n/2) ())

However, you can do this:

let rec foo = [| (fun () -> 0); (fun () -> foo.(0) ()) |];;

(here, the array is created by the compiler itself, so it knows its

I hope this is clear.

Stephane Glondu.