Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

F# Multidimensional Array Types

What's the difference between 'a[,,] and 'a[][][]? They both represent 3-d arrays. It makes me write array3d.[x].[y].[z] instead of array3d.[x, y, z].

Why I can't do the following?

> let array2d : int[,] = Array2D.zeroCreate 10 10;;
> let array1d = array2d.[0];;

error FS0001: This expression was expected to have type
    'a []    
but here has type
    int [,]
like image 899
Ming-Tang Avatar asked May 25 '10 23:05

Ming-Tang


2 Answers

The difference is that 'a[][] represents an array of arrays (of possibly different lengths), while in 'a[,], represents a rectangular 2D array. The first type is also called jagged arrays and the second type is called multidimensional arrays. The difference is the same as in C#, so you may want to look at the C# documentation for jagged arrays and multidimensional arrays. There is also an excelent documentation in the F# WikiBook.

To demonstrate this using a picture, a value of type 'a[][] can look like this:

0 1 2 3 4
5 6
7 8 9 0 1

While a value of type a[,] will always be a rectangle and may look for example like this:

0 1 2 3
4 5 6 7
8 9 0 1

To get a single "line" of a multidimensional array, you can use the slice notation:

let row = array2d.[0,*];;

See https://learn.microsoft.com/en-us/dotnet/fsharp/language-reference/arrays#array-slicing-and-multidimensional-arrays

like image 162
Tomas Petricek Avatar answered Nov 16 '22 02:11

Tomas Petricek


As of F# 3.1 (2013) things are simpler:

As of F# 3.1, you can decompose a multidimensional array into subarrays of the same or lower dimension. For example, you can obtain a vector from a matrix by specifying a single row or column.

// Get row 3 from a matrix as a vector:
matrix.[3, *]

// Get column 3 from a matrix as a vector:
matrix.[*, 3]

See https://learn.microsoft.com/en-us/dotnet/fsharp/language-reference/arrays#array-slicing-and-multidimensional-arrays

like image 34
Colonel Panic Avatar answered Nov 16 '22 03:11

Colonel Panic