Version française
Home     About     Download     Resources     Contact us    
Browse thread
[Caml-list] Recursive lists
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: Alex Baretta <alex@b...>
Subject: Re: [Caml-list] Recursive lists
sejourne_kevin wrote:

> 
> (** Take a list and connect the end on the beginning
>    Copyright : Kévin ;)
> *)
> let cycle l =
>   let rl= ref l in
>   let rec go_fin = function
>       [] -> invalid_arg "cycle:[] can't be !"
>     | [x] as f -> Obj.set_field (Obj.repr f) 1 (Obj.repr !rl);l
>     | x::reste-> go_fin reste
>   in go_fin l
> ;;
> I haven't test GC issu.
> 

Nice code. So clean. So idiomatic. So type-safe... Well, it's really 
this Obj stuff is the best we can do with the current intuition of 
recursive values implemented in the Ocaml compiler.

Let me suggest a slightly safer version:

let cycle l =
   let l = List.rev (List.rev l) in
   let rl= ref l in
   let rec go_fin = function
       [] -> invalid_arg "cycle:[] can't be !"
     | [x] as f -> Obj.set_field (Obj.repr f) 1 (Obj.repr !rl);
     | x::reste-> go_fin reste
   in go_fin l

This first duplicates the original list so that aliasing is not an issue.

BTW, I've just discovered that List.append is safe with respect to an 
infinite second argurment, which is a totally desirable property. It is 
open to discussion as to whether append should analyze l1 for cyclicity

Alex

-------------------
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