Browse thread
Preferred Way to Split a List
[
Home
]
[ Index:
by date
|
by threads
]
[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
[ 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 -> ('a -> 'a) -> 'a -> 'a = <fun>
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 = <fun>
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 = <fun>
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>