From mboxrd@z Thu Jan 1 00:00:00 1970 Return-Path: X-Spam-Checker-Version: SpamAssassin 3.1.3 (2006-06-01) on yquem.inria.fr X-Spam-Level: X-Spam-Status: No, score=0.0 required=5.0 tests=AWL autolearn=disabled version=3.1.3 X-Original-To: caml-list@yquem.inria.fr Delivered-To: caml-list@yquem.inria.fr Received: from mail1-relais-roc.national.inria.fr (mail1-relais-roc.national.inria.fr [192.134.164.82]) by yquem.inria.fr (Postfix) with ESMTP id 33097BC6B for ; Tue, 30 Oct 2007 09:00:04 +0100 (CET) X-IronPort-Anti-Spam-Filtered: true X-IronPort-Anti-Spam-Result: AgAAACOBJkfUnw7Xnmdsb2JhbACCOIwnAgEBBwQGERg X-IronPort-AV: E=Sophos;i="4.21,346,1188770400"; d="scan'208";a="3819833" Received: from fhw-relay07.plus.net ([212.159.14.215]) by mail1-smtp-roc.national.inria.fr with ESMTP; 30 Oct 2007 09:00:03 +0100 Received: from [80.229.56.224] (helo=beast.local) by fhw-relay07.plus.net with esmtp (Exim) id 1Imm14-0003ws-MU for caml-list@yquem.inria.fr; Tue, 30 Oct 2007 08:00:02 +0000 From: Jon Harrop Organization: Flying Frog Consultancy Ltd. To: caml-list@yquem.inria.fr Subject: Re: [Caml-list] Preferred Way to Split a List Date: Tue, 30 Oct 2007 07:50:24 +0000 User-Agent: KMail/1.9.5 References: <47266DB7.1020009@SmokejumperIT.com> In-Reply-To: <47266DB7.1020009@SmokejumperIT.com> MIME-Version: 1.0 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: 7bit Content-Disposition: inline Message-Id: <200710300750.26912.jon@ffconsultancy.com> X-Spam: no; 0.00; combinator:01 val:01 val:01 frog:98 wrote:01 rec:01 caml-list:01 int:01 int:01 arbitrary:02 arbitrary:02 arg:03 tend:03 element:03 let:03 On Monday 29 October 2007 23:33, Robert Fischer wrote: > What is the preferred way to split a list into two, at an arbitrary > point? There's lots of ways you could do it, but I'm not sure if > there's a standard best practice for this. I tend to write a combinator that nests an arbitrary number of function applications: # let rec nest n f x = if n=0 then x else nest (n-1) f (f x);; val nest : int -> ('a -> 'a) -> 'a -> 'a = and then apply this to a function that moves head elements: # let aux = function | front, h::back -> h::front, back | _ -> invalid_arg "aux";; val aux : 'a list * 'a list -> 'a list * 'a list = Then I write a "chop" function in terms of those two: # let chop n list = nest n aux ([], list);; val chop : int -> 'a list -> 'a list * 'a list = For example, splitting after the fourth element: # chop 4 [1;2;3;4;5;6;7;8;9];; - : int list * int list = ([4; 3; 2; 1], [5; 6; 7; 8; 9]) Note that the front list is reversed. PS: Ignore any responses that even mention Obj. -- Dr Jon D Harrop, Flying Frog Consultancy Ltd. http://www.ffconsultancy.com/products/?e