F # take a list, return a list of tuples

I did some research and I can see that the List.zip function takes two lists and returns one list of tuples, but how do you change one list to a list of tuples?

let rec combinePair xs =
    match xs with
    | [] -> []
    | [x1] -> []
    | x1::x2::x3::xs -> [(x1, x2)]
    | x1::x2::xs -> [(x1, x2)] 

If there is an odd number of elements in the list, the last element should be discarded; if there is an even number of elements, they should be returned as a list of tuples. for instance

combinePair [x1; x2; x3; x4] = [(x1, x2); (x3, x4)]
+4
source share
2 answers

Your code is almost missing.

Here's the thinking:

  • when an empty list is given, the result will be an empty list (you already got this).
  • when a list of one element is given, the result will be an empty list (it turned out too).
  • , , - .

F #:

let rec combinePair xs =
    match xs with
    | [] | [_] -> []
    | x1::x2::rest -> (x1, x2) :: (combinePair rest)

( , , [] | [_] ->)

+4

, , , :

let xsOdd =  [1;2;3;4;5]

List.chunkBySize 2 xsOdd 
    |> List.filter (fun x -> x.Length = 2) 
    |> List.map (fun x -> x.[0],x.[1])
//val it : (int * int) list = [(1, 2); (3, 4)]
+4

Source: https://habr.com/ru/post/1670014/


All Articles