Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

F# - Convert Jagged Array to Array2D

@scrwtp provides a very useful function (toJagged):

let toJagged<'a> (arr: 'a[,]) : 'a [][] = 
    [| for x in 0 .. Array2D.length1 arr - 1 do
           yield [| for y in 0 .. Array2D.length2 arr - 1 -> arr.[x, y] |]
    |]

that converts from a 2D array to a jagged array. Is there an equivalent function available (toArray2D) for converting from a jagged array to a 2D array (assuming each row in the jagged array has the same number of elements)?

like image 541
matekus Avatar asked Mar 07 '23 03:03

matekus


1 Answers

There is a built-in function array2D that does exactly this:

array2D 
  [| [| 1; 2 |]
     [| 3; 4 |] |]

The array2D function has a type seq<#seq<'T>> -> 'T[,] so it is more general - it can convert any sequence of sequences of values to a 2D array, but since a jagged array is a sequence of sequences, this is all you need. Note that this throws if your nested arrays have different lengths.

like image 87
Tomas Petricek Avatar answered Mar 15 '23 10:03

Tomas Petricek