Version française
Home     About     Download     Resources     Contact us    
Browse thread
Preferred Way to Split a List
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: Karl Zilles <zilles@1...>
Subject: Re: [Caml-list] Preferred Way to Split a List
Julien Moutinho wrote:
 > (* may trash the given list but tail-recursive *)
 > # let magic_split l f =
 >     let rec aux p =
 >         function
 >         | [] -> l,[]
 >         | h::t as b ->
 >             if f h then aux (Some b) t
 >             else match p with None -> [],l
 >             | Some p -> (Obj.magic p).(1) <- None; l,b
 >     in aux None l;;
 > val magic_split : 'a list -> ('a -> bool) -> 'a list * 'a list = <fun>
 > # let l = [1;2;3;4;5;6];;
 > val l : int list = [1; 2; 3; 4; 5; 6]
 > # magic_split l ((>=) 4);;
 > - : int list * int list = ([1; 2; 3; 4], [5; 6])
 > # l;;
 > - : int list = [1; 2; 3; 4]

Wow, this looks like a horrible idea!  You're modifying a non-mutable 
data structure and using object magic.  This leads to madness:

# let test () = magic_split [1; 2; 3; 4; 5; 6] ((>=) 4);;
val test : unit -> int list * int list = <fun>
# test ();;
- : int list * int list = ([1; 2; 3; 4], [5; 6])
# test ();;
- : int list * int list = ([1; 2; 3; 4], [])

I'm sure you're aware of this, but to suggest this as an answer to his 
question...