Version française
Home     About     Download     Resources     Contact us    

This site is updated infrequently. For up-to-date information, please visit the new OCaml website at

Browse thread
Re: cyclic value construction ("let rec")
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: Markus Mottl <mottl@m...>
Subject: Re: cyclic value construction ("let rec")
> It would be interesting to know whether people have other workarounds.
> Also, a generic graph module which would implement "map", "iter" etc. in a 
> cycle-safe way (like Marshal) would perhaps be interesting in the
> 'user-contributed stdlib extension'...

You will probably always have to rely on "unsafe" things for such
purposes.  My quick hack for problems like this looks as follows:

  type 'a node = { data : 'a; next : 'a node }

  let make_circle n : 'a node =
    let module Dummy = struct
      type 'a t = { data : 'a; mutable next : 'a t } end in
    let res = { = n; = Obj.magic 0 } in <- res;
    Obj.magic res

  let rec iter f node = f; iter f

  let _ = iter (fun x -> print_int x; print_newline ()) (make_circle 42)

Type "'a node" is immutable from the outside. However, exploiting the
undocumented (good reason for this ;-) type casting features of OCaml,
one can cheat and define an identical type within a local module -
which is mutable!

Initialisation, too, relies on "unsafe" features - we simply put a
reference to a dummy value into the slot until it can be filled with the
"right" value. The return value is cast back again to the "global type"
as indicated in the type restriction in the definition of "make_circle"
- this is important, because otherwise you can crash your program (it
would have "any" type).

As far as I know, this should be safe, because the GC doesn't care
about the static types of the values - it only looks at the value tags
at runtime. Of course, the above will only work as long as the memory
layout of the "local" type agrees with the one of the "global type".

Thus, you can confine the "unsafe" part to specific functions (e.g.
"make_circle"). The iteration function "iter" does not change anything
and can therefore work on the "global" type.

Best regards,
Markus Mottl

Markus Mottl,,