Here's one way to zip them back together. Please note that this has the same prerequisites as List.zip, in that both lists should be of the same length (or, at least, the second list should not be shorter than the first).

1
2
3
4
let rec altzip x y =
  match x with
  | _::_ -> (List.hd x) :: (List.hd y) :: altzip (List.tl x) (List.tl y)
  | _ -> [];;

If you want to deal with uneven size lists:

1
2
3
4
5
6
let rec altzip2 x y =
  match x,y with
  | _::_, _::_ -> (List.hd x) :: (List.hd y) :: altzip2 (List.tl x) (List.tl y)
  | _::_, _ -> x
  | _, _::_ -> y
  | _, _ -> [];;

It should be easy to thread an accumulator to make these functions tail-recursive. Finally, if you want to use the built-in F# List API:

1
2
let altzip3 x y =
  List.fold_left2 (fun seed one two -> seed @ [one; two]) [] x y

Regards,

z.

By on 12/30/2007 7:02 PM ()

Wow, another nice one z.

I'd completely overlooked the fold_left2 function. I sure wish there were some good examples of how to use each of these List.* functions. There's a ton of functionality there.

Thanks :)

By on 1/2/2008 9:47 AM ()
IntelliFactory Offices Copyright (c) 2011-2012 IntelliFactory. All rights reserved.
Home | Products | Consulting | Trainings | Blogs | Jobs | Contact Us | Terms of Use | Privacy Policy | Cookie Policy
Built with WebSharper