Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

F# convert array to array of tuples

Tags:

f#

Let's say I have an array

let arr = [|1;2;3;4;5;6|]

I would like to convert it to something like

[|(1,2);(3,4);(5,6)|]

I've seen Seq.window but this one is going to generate something like

[|(1,2);(2,3);(3,4);(4,5);(5,6)|]

which is not what I want

like image 787
AlexanderM Avatar asked May 07 '26 22:05

AlexanderM


2 Answers

You can use Array.chunkBySize and then map each sub-array into tuples:

let input = [|1..10|]
Array.chunkBySize 2 list |> Array.map (fun xs -> (xs.[0], xs.[1]))
like image 113
Slugart Avatar answered May 10 '26 16:05

Slugart


@Slugart's accepted answer is the best approach (IMO) assuming you know that the array has an even number of elements, but here's another approach that doesn't throw an exception if there does happen to be an odd number (it just omits the last trailing element):

let arr = [|1;2;3;4;5|]
seq { for i in 0 .. 2 .. arr.Length - 2 -> (arr.[i], arr.[i+1]) } |> Seq.toArray
like image 20
Sven Grosen Avatar answered May 10 '26 18:05

Sven Grosen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!