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: Robert Fischer <robert@f...>
Subject: Re: [Caml-list] Preferred Way to Split a List
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
  <meta content="text/html;charset=ISO-8859-1" http-equiv="Content-Type">
</head>
<body bgcolor="#ffffff" text="#000000">
Thanks for the sane response.<br>
<br>
~~ Robert.<br>
<br>
Jon Harrop wrote:
<blockquote cite="mid:200710300750.26912.jon@ffconsultancy.com"
 type="cite">
  <pre wrap="">On Monday 29 October 2007 23:33, Robert Fischer wrote:
  </pre>
  <blockquote type="cite">
    <pre wrap="">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.
    </pre>
  </blockquote>
  <pre wrap=""><!---->
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 -&gt; ('a -&gt; 'a) -&gt; 'a -&gt; 'a = &lt;fun&gt;

and then apply this to a function that moves head elements:

# let aux = function
    | front, h::back -&gt; h::front, back
    | _ -&gt; invalid_arg "aux";;
val aux : 'a list * 'a list -&gt; 'a list * 'a list = &lt;fun&gt;

Then I write a "chop" function in terms of those two:

# let chop n list =
    nest n aux ([], list);;
val chop : int -&gt; 'a list -&gt; 'a list * 'a list = &lt;fun&gt;

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.
  </pre>
</blockquote>
</body>
</html>