Need help for a problem

Hello! I’ve been struggling for a few days already with a given task. What I am supposed to do is create a list of tuples from a list ’a list -> (’a * ’a) list where the first element gets paired with the last, the second with the pre-last etc. and if the list is odd, the middle element is removed.

For example:

    func [1;2;3;4;5;6;7];;
    - : int list = [(1,7);(2,6);(3,5)]

What I’ve tried is using List.combine on the original list and its reverse but it gives me all the elements backwards, which is what I do not want, also I’ve tried multiple recursive functions but to no avail. My main problem is converting from a list to a list of tuples.

Thanks for your help!

You can do the combine/reverse thing and take the right number of elements:

let rec take n = function
  | [] -> []
  | x::xs ->
    if n <= 0 then []
    else x::take (n - 1) xs

let pairs list =
  take (List.length list / 2) (List.combine list (List.rev list))

A more efficient approach would fuse length/rev and take/combine to avoid the redundant traversals.

Thank you very much brate!