5

@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)?

matekus
  • 778
  • 3
  • 14

1 Answers1

10

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.

Tomas Petricek
  • 240,744
  • 19
  • 378
  • 553