This site is updated infrequently. For up-to-date information, please visit the new OCaml website at ocaml.org.

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: 2007-10-30 (08:00) From: Jon Harrop Subject: Re: [Caml-list] Preferred Way to Split a List
```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 = <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.
--
Dr Jon D Harrop, Flying Frog Consultancy Ltd.
http://www.ffconsultancy.com/products/?e

```